學習背景
項目中經常要解析和生成Excel文件,最常用的開源組件有poi與jxl。jxl是韓國人開發的,發行較早,但是更新的很慢,目前似乎還不支持excel2007。poi是apache下的一個子項目,poi應該是處理ms的office系列文檔最好的組件了。
經常用的類一般都在org.apache.poi.hssf.usermodel(excel2003)或org.apache.poi.xssf.usermodel
(excel2007)。
- 工作薄: WorkBook是操作Excel的入口,HSSFWorkbook, XSSFWorkbook實現了該接口。
- 頁:Sheet表示工作薄的分頁。HSSFSheet, XSSFChartSheet, XSSFDialogsheet, XSSFSheet實現了該接口。
- Row:表示頁中的一行。HSSFRow, XSSFRow實現了該接口。
- Cell:行中的一個單元格。HSSFCell, XSSFCell實現了該接口。
從上面的介紹得知:頁是通過工作薄對象創建的,行是通過頁對象創建的,單元格是通過行對象創建的。接下來,我們就開始發掘poi的強大功能吧。
1、maven 配置poi。支持2007
<dependencies>
<dependency>
<groupId> org.apache.poi</groupId >
<artifactId> poi</artifactId >
<version> 3.10-FINAL</version >
</dependency>
<dependency>
<groupId> org.apache.poi</groupId >
<artifactId> poi-ooxml</artifactId>
<version> 3.10-FINAL</version >
</dependency>
</dependencies>
注:綠色添加jar包爲支持2007
3、封裝一個簡單的對單元格操作的方法
//設置單元格水平垂直對齊方式
public static void createCell(Workbook
workbook,Row row, int column,Short
halign,Short valign){
Cell cell = row.createCell(column);
cell.setCellValue( new XSSFRichTextString("ALIGN
IT" ));
CellStyle cellStyle = workbook.createCellStyle();
cellStyle.setAlignment(halign);
cellStyle.setVerticalAlignment(valign);
cell.setCellStyle(cellStyle);
}
4、一個簡單的poi操作excel的例子。基於maven的項目。可作爲poi例子的建議模版。