近日,使用POI解析excel,發現2003版本的excel解析與2007版本的excel解析存在問題.特此總結:
1.所需jar包 :
2.java類代碼(讀取excel文件):
public void testPoi(String path) throws Exception{
File file = new File(path);
//解決版本兼容問題
Workbook wb = null;
try {
wb = new HSSFWorkbook(new FileInputStream(file));//支持excel 2003
} catch (Exception e) {
wb = new XSSFWorkbook(new FileInputStream(file));//支持excel 2007
}
//獲取第一張表
Sheet sheet = wb.getSheetAt(0);
System.out.println(sheet.getLastRowNum());
//sheet.getLastRowNum() :得到表的最后一行的編碼(編碼從0開始)
for (int i = 0; i <= sheet.getLastRowNum(); i++) {
//得到行
Row row = sheet.getRow(i);
for(int j=0; j < 2; j++) {
//得到列
Cell cell = row.getCell(j);
//取某一列的值
System.out.println(cell.getStringCellValue());
}
}
}