POI 使用总结
之前用POI做了一段时间的报表,也对POI的一些方法重写了,用起来还算方便。也没什么特别的,主要就是对HSSFWorkbook,HSSFSheet,HSSFRow, HSSFCell的操作了,掌握了对这四个东西的控制,你想怎么写就怎么写。
1,首先写一个abstract class用来overwrite HSSF。
package com.eagle.excel;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.util.ArrayList;import java.util.Calendar;import org.apache.poi.hssf.usermodel.HSSFRow;import org.apache.poi.hssf.usermodel.HSSFSheet;import org.apache.poi.hssf.usermodel.HSSFWorkbook;import org.apache.poi.hssf.util.Region;/** * @author eyas * @version 1.0 * @date Apr 28, 2007 10:43:26 PM */public class CreateExcelFile extends ExportInfoToExcel implements ExportInfoInterface{private HSSFWorkbook workbook;private HSSFSheet sheet;private ArrayList dataList;private Calendar date; private String[] columns; private int lineX = 0;public CreateExcelFile (){ //initialized someone arguments}@Overrideprotected void createBody(){HSSFRow bodyTile = sheet.createRow(lineX++);for (int i = 0; i < columns.length; i++){createCell(bodyTile.createCell((short) i), columns[i]);}HSSFRow bodyRow;for (int i = 0; i < dataList.size(); i++){ bodyRow = sheet.createRow(lineX++); createCell(null,bodyRow.createCell((short) 0),(i+1)); createCell(null,bodyRow.createCell((short) 1),"eyas"); createCell(null,bodyRow.createCell((short) 2),"software"); ...}}@Overrideprotected void createFoot(){HSSFRow totalRow = sheet.createRow(lineX++); createCell(null,bodyRow.createCell((short) 0),"total data");}@Overrideprotected void createHead(){lineX = 0;sheet.addMergedRegion(new Region(0, (short) 0, 0, (short) 12));HSSFRow headRow0 = sheet.createRow(lineX++);createCell(null,headRow0.createCell((short) 0), "My Excel Report");}public void produceExportFile(File exportfile) throws Exception{try{workbook = new HSSFWorkbook();sheet = workbook.createSheet("First Page");createHead();createBody();FileOutputStream fw = new FileOutputStream(exportfile);workbook.write(fw);fw.flush();fw.close();workbook = null;sheet = null;fw = null; System.out.println("Export success!");} catch (IOException ioe){ioe.printStackTrace();}catch (Exception e){e.printStackTrace();}}public void setColumns(String[] columns){this.columns = columns;}public void setDataList(ArrayList dataList){this.dataList = dataList;}public void setOtherArg(Object arg1){}public void setDate(Calendar date){this.date = date;}}