使用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();
}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章