学习背景
项目中经常要解析和生成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
2、依赖的jar包
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例子的建议模版。