Aka*_*shi 1 java apache excel apache-poi
我已经使用Apache POI库成功读取了excel文件.但是,我收到了一个奇怪的行为,我不确定它为什么会发生.
如果我创建一个新的excel文件,调整所需的数据,如下所示:

根本不读取在电子邮件列的第一个设置的空单元格(忽略).
但是,如果我修改文件并更改同一文件的字体或字体大小,Apache POI会成功读取空的电子邮件单元格.
默认字体设置(空单元格未读取):

我从方法中收到的数组:
[Hari Krishna, 445444, 986544544]
Run Code Online (Sandbox Code Playgroud)
更改字体大小(空单元格成功读取):

我从方法中收到的数组:
[Hari Krishna, 445444, 986544544, ]
Run Code Online (Sandbox Code Playgroud)
以下是我用来阅读excel文件的完整代码:
public static List importExcelFile(String filePath, String fileName) {
DataFormatter formatter = new DataFormatter(Locale.UK);
// stores data from excel file
List excelDataList = new ArrayList();
try {
// Import file from source destination
FileInputStream file = new FileInputStream(new File(filePath.concat(File.separator.concat(fileName))));
// Get the workbook instance for XLS file
XSSFWorkbook workbook = new XSSFWorkbook(file);
// workbook.setMissingCellPolicy(Row.RETURN_BLANK_AS_NULL);
// Get first sheet from the workbook
XSSFSheet sheet = workbook.getSheetAt(0);
// Iterate through each rows from first sheet
Iterator<Row> rowIterator = sheet.iterator();
// Skip first row, since it is header row
rowIterator.next();
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
int nextCell = 1;
int currentCell = 0;
// add data of each row
ArrayList rowList = new ArrayList();
// For each row, iterate through each columns
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
currentCell = cell.getColumnIndex();
if (currentCell >= nextCell) {
int diffInCellCount = currentCell - nextCell;
for (int nullLoop = 0; nullLoop <= diffInCellCount; nullLoop++) {
rowList.add(" ");
nextCell++;
}
}
switch (cell.getCellType()) {
case Cell.CELL_TYPE_BOOLEAN:
rowList.add(cell.getBooleanCellValue());
break;
case Cell.CELL_TYPE_NUMERIC:
if (DateUtil.isCellDateFormatted(cell)) {
String date = formatter.formatCellValue(cell);
rowList.add(date);
} else {
rowList.add(cell.getNumericCellValue());
}
break;
case Cell.CELL_TYPE_STRING:
rowList.add(cell.getStringCellValue());
break;
case Cell.CELL_TYPE_BLANK:
rowList.add(" ");
break;
case Cell.CELL_TYPE_ERROR:
rowList.add(" ");
break;
default:
break;
}
nextCell++;
}
excelDataList.add(rowList);
}
file.close();
} catch (FileNotFoundException e) {
System.out.println(e.toString());
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
return excelDataList;
}
Run Code Online (Sandbox Code Playgroud)
原因是当您设置单元格的字体大小时,Excel需要一种方法来知道单元格具有不同的字体(通常情况下CellStyle).当您从默认值更改字体大小时,Excel创建了一个空白单元格并给它一个单元格样式 - 字体大小为10.因为它CellStyle是一个属性Cell,Excel需要一个Cell所以它可以存储CellStyle它.
当你用a读取Cells时Iterator<Cell>,它只返回那些Cell存在的s.在更改字体大小之前,"Hari Krishna"的"电子邮件"单元格不存在.字体大小改变后,现在"Hari Krishna"的"电子邮件"单元格存在,即使它是空白的.
如果你想要空白值,即使没有字体大小改变,那么你也不能使用Iterator,因为它不会返回Cell- 它不存在.您可以使用一个标准for的上环Row对象,使用MissingCellPolicy的CREATE_NULL_AS_BLANK.
如果要跳过空白值,无论是否有字体大小更改,您应该只是跳过类型为的单元格CELL_TYPE_BLANK.从您的switch陈述中删除该案例.