一:簡介html
利用POI工具能夠導出word,excel,ppt等office文件java
二:程序代碼示例apache
package com.wang.test; import java.io.File; import java.io.FileOutputStream; import java.util.Calendar; import java.util.Date; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFCellStyle; import org.apache.poi.hssf.usermodel.HSSFDataFormat; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; public class Test { public static void main(String[] args) throws Exception{ //建立工做簿 HSSFWorkbook wb=new HSSFWorkbook(); //建立工做表 HSSFSheet sheet1=wb.createSheet("first sheet"); HSSFSheet sheet2=wb.createSheet("second sheet"); //建立row HSSFRow row=sheet1.createRow(0); //建立單元格 HSSFCell cell=row.createCell(0); cell.setCellValue(false); row.createCell(1).setCellValue(Calendar.getInstance()); row.createCell(2).setCellValue(new Date()); row.createCell(3).setCellValue(123456.654321); String str="abcdefghi"; //建立數據格式對象 HSSFDataFormat format=wb.createDataFormat(); //建立單元格樣式 HSSFCellStyle style=wb.createCellStyle(); //對日期格式化 style.setDataFormat(format.getFormat("yyyy-MM-dd HH:mm:ss")); //應用樣式給單元格 row.getCell(1).setCellStyle(style); row.getCell(2).setCellStyle(style); //對double值格式化 style=wb.createCellStyle(); style.setDataFormat(format.getFormat("#.00")); row.getCell(3).setCellStyle(style); //設置列寬,注意:列寬相對於sheet的。 sheet1.setColumnWidth(1, 3000); //也能夠自動調節列寬 sheet1.autoSizeColumn(2); sheet1.setColumnWidth(4, 7000); //自動迴繞文本,把太長的字符串換行顯示 row=sheet1.createRow(1); row.createCell(0).setCellValue("左上"); row.createCell(1).setCellValue("中間"); row.createCell(2).setCellValue("右下"); //設置行高 row.setHeightInPoints(50); sheet1.setColumnWidth(0, 5000); sheet1.setColumnWidth(1, 5000); sheet1.setColumnWidth(2, 5000); //設置對齊方式--左上 style=wb.createCellStyle(); style.setAlignment(HSSFCellStyle.ALIGN_LEFT); style.setVerticalAlignment(HSSFCellStyle.VERTICAL_TOP); row.getCell(0).setCellStyle(style); //設置對齊方式--中間 style=wb.createCellStyle(); style.setAlignment(HSSFCellStyle.ALIGN_CENTER); style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); row.getCell(1).setCellStyle(style); //設置對齊方式--右下 style=wb.createCellStyle(); style.setAlignment(HSSFCellStyle.ALIGN_RIGHT); style.setVerticalAlignment(HSSFCellStyle.VERTICAL_BOTTOM); row.getCell(2).setCellStyle(style); //重點:計算列 row=sheet1.createRow(3); row.createCell(0).setCellValue(13); row.createCell(1).setCellValue(45); row.createCell(2).setCellValue(25); row.createCell(3).setCellFormula("sum(A4:C4)"); //導出到磁盤 wb.write(new FileOutputStream(new File("f:/poi.xls"))); } } 效果: