使用POI 3.8编写可以同时解析excel2003/2007的代码

目前最新的poi-3.8-20120326.jar已经可以同时支持office 2003和office 2007的文档处理,最近用它处理过xls和xlsx两种格式的文件,做个笔记。

据我了解,POI用于处理xls的API都是HSSF开头的,比如HSSFWorkbook和HSSFSheet;而用于处理xlsx的API是XSSF开头的,比如XSSFWorkbook。

如果只有这两种的话,要同时支持xls和xlsx两种格式,就要写两份代码,何其麻烦。

幸好还有第三种选择,那就是没有上述两种前缀的API,比如Workbook和Sheet等,都在org.apache.poi.ss.usermodel包下面。没有前缀,显然意味着这是一种通用的excel处理API了。

使用起来也很简单:

if (fileName.endsWith(".xlsx") || fileName.endsWith(".xls")){
FileInputStream inputStream = new FileInputStream(file);
Workbook workbook = WorkbookFactory.create(inputStream);
analyzeWorkbook(workbook);
}

下面是analyzeWorkbook的部分代码:

Sheet sheet = workbook.getSheetAt(0);//第一个表单
Row excelRow = null;
Map<String,Object> row = null;
int rowCount = sheet.getLastRowNum();
//循环处理每个格子
for (int j = 0 ; j <= rowCount ; j++){
excelRow = sheet.getRow(j);
if (excelRow != null){
row = new HashMap<String,Object>();
for (int i = 0 ; i < colModel.size() ; i++){
Cell cell = excelRow.getCell(i);
if (cell == null ){
row.put(colModel.get(i).toString(), "");
}
else {
row.put(colModel.get(i).toString(), getCellValue(cell));
}
}
rows.add(row);
}
}

getCellValue的:

private Object getCellValue(Cell cell){
int cellType = cell.getCellType();

switch (cellType) {
case Cell.CELL_TYPE_STRING:
return cell.getStringCellValue();
case Cell.CELL_TYPE_NUMERIC:
if (DateUtil.isCellDateFormatted(cell)) {
Date date = cell.getDateCellValue();
return DateUtil.toString(date, "yyyy-MM-dd");
}
else {
return cell.getNumericCellValue();
}
case Cell.CELL_TYPE_BOOLEAN:
return cell.getBooleanCellValue();
case Cell.CELL_TYPE_FORMULA:
case Cell.CELL_TYPE_BLANK:
case Cell.CELL_TYPE_ERROR:
default: return cell.getStringCellValue();
}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章