在Java中使用POI读取Excel

我有一个Excel文件有几个string数据types列,一个数字列和一个date列。 我正在使用Apache POI来读取文件。 下面是如何处理数据types

Cell cell = sheet.getRow(i).getCell(j); if(cell!=null){ switch(cell.getCellType()){ case Cell.CELL_TYPE_STRING: cellValue = cell.getStringCellValue(); break; case Cell.CELL_TYPE_NUMERIC: DateFormat df = new SimpleDateFormat("MM/dd/yyyy"); Date cellDate = cell.getDateCellValue(); cellValue = df.format(cellDate); break; case Cell.CELL_TYPE_BLANK: break; default : } } 

这适用于String和date数据types。 但是对于数字,它将该值转换为date。 我知道这是因为处理有问题。 你可以请教如何适应处理数字和date数据types?

谢谢,山姆。

如果您知道每列的数据types,您甚至不必每次检查单元格types:

 switch (columnIndex) { case 0: case 1: case 2: { cellValue = cell.getStringCellValue(); break; } case 3: { Date cellDate = cell.getDateCellValue(); // ... break; } case 4: { cellValue = cell.getNumericCellValue(); break; } } 

如果你的专栏可以包含date和数字,你可以试试这个

 import org.apache.poi.ss.usermodel.DateUtil; case Cell.CELL_TYPE_NUMERIC: if (DateUtil.isCellDateFormatted(cell)) { // your code for date handling } else { cellValue = cell.getNumericCellValue(); }