在 java 中使用 POI 阅读 Excel
Reading Excel using POI in java
我有一个 excel 文件,其中有几个字符串数据类型列、一个数字列和一个日期列。我正在使用 Apache POI 读取文件。
下面是我如何处理数据类型
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 :
}
}
这适用于字符串和日期数据类型。但是对于数字,它将值转换为日期。我知道这是因为处理有问题。您能否就如何同时处理数字和日期数据类型提出建议?
谢谢,
山姆。
如果你知道每列属于什么数据类型,你甚至不必每次都检查单元格类型:
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;
}
}
如果您的列可以同时包含日期和数字,您可以试试这个
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();
}
我有一个 excel 文件,其中有几个字符串数据类型列、一个数字列和一个日期列。我正在使用 Apache POI 读取文件。 下面是我如何处理数据类型
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 :
}
}
这适用于字符串和日期数据类型。但是对于数字,它将值转换为日期。我知道这是因为处理有问题。您能否就如何同时处理数字和日期数据类型提出建议?
谢谢, 山姆。
如果你知道每列属于什么数据类型,你甚至不必每次都检查单元格类型:
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;
}
}
如果您的列可以同时包含日期和数字,您可以试试这个
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();
}