标签:
package com.file.properties; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.util.Hashtable; import org.apache.poi.hssf.usermodel.HSSFCellStyle; import org.apache.poi.hssf.util.HSSFColor; import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.xssf.usermodel.XSSFCell; import org.apache.poi.xssf.usermodel.XSSFRow; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; class WriteExcel { @SuppressWarnings("rawtypes") static void saveToExcelFile(File writeFile,Hashtable table) { try { // write data to Excel file XSSFWorkbook wb; XSSFSheet sheet; XSSFRow row; XSSFCell cell; int rowIndex = 0; if (writeFile.exists()) { InputStream excelFile = new FileInputStream(writeFile); wb = new XSSFWorkbook(excelFile); sheet = wb.getSheetAt(0); rowIndex = sheet.getLastRowNum(); rowIndex += 1; row = sheet.createRow(rowIndex); } else { wb = new XSSFWorkbook(); sheet = wb.createSheet(); row = sheet.createRow(0); cell = row.createCell(0); cell.setCellValue("URL"); cell = row.createCell(1); cell.setCellValue("PageRank"); cell = row.createCell(2); cell.setCellValue("AlexaRank"); row = sheet.createRow(1); } CellStyle cs = wb.createCellStyle(); cs.setFillForegroundColor(HSSFColor.GREEN.index); cs.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND); cell = row.createCell(0); cell.setCellValue(table.get("URL").toString()); cell = row.createCell(1); if (Integer.parseInt(table.get("PageRank").toString()) >= 5) cell.setCellStyle(cs); cell.setCellValue(table.get("PageRank").toString()); cell = row.createCell(2); cell.setCellValue(table.get("AlexaRank").toString()); FileOutputStream out = new FileOutputStream(writeFile); wb.write(out); out.flush(); out.close(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * @param args */ @SuppressWarnings({ "rawtypes", "unchecked" }) public static void main(String[] args) { // TODO Auto-generated method stub File writeFile = new File("D:\\SoapUIStudy\\writeExcel.xlsx"); Hashtable table = new Hashtable(); table.put("URL","http:\\cn.bing.com"); table.put("PageRank","5"); table.put("AlexaRank","13658988546"); saveToExcelFile(writeFile,table); } }
These 4 JARs are needed to run above codes:
Run 2 times, the excel will show like below :
[Java]Write Excel File Using Apache POI API
标签:
原文地址:http://www.cnblogs.com/MasterMonkInTemple/p/4581451.html