我已经使用Apache POI库成功读取了excel文件。但是,我收到了一个奇怪的行为,我不确定它为什么会发生。
如果我创建一个新的excel文件,并调整所需数据,如下所示:
根本不读取在电子邮件列的第一个设置的空单元格(忽略)。
但是,如果我修改文件并更改同一文件的字体或字体大小,Apache POI会成功读取空的电子邮件单元格。
默认字体设置(空单元格未读取):
我从方法中收到的数组:
[Hari Krishna, 445444, 986544544]
更改了字体大小(空单元格成功读取):
我从方法中收到的数组:
[Hari Krishna, 445444, 986544544, ]
以下是我用来阅读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;
}
答案 0 :(得分:5)
原因是当您设置单元格的字体大小时,Excel需要一种方法来知道单元格具有不同的字体(通常为CellStyle
)。当您从默认值更改字体大小时,Excel创建了一个空白单元格并为其指定了单元格样式 - 字体大小为10.因为CellStyle
是Cell
的属性,Excel需要{ {1}}因此它可以存储Cell
。
当您使用CellStyle
阅读Cell
时,它只会返回存在的Iterator<Cell>
个。在更改字体大小之前,&#34;电子邮件&#34; &#34; Hari Krishna&#34;不存在。字体大小改变后,现在&#34;电子邮件&#34; &#34; Hari Krishna&#34;存在,即使它是空白的。
如果您想要空白值,即使没有更改字体大小,也无法使用Cell
,因为它不会返回Iterator
- 它不存在。您可以使用MissingCellPolicy
of CREATE_NULL_AS_BLANK
在Cell
对象上使用标准for
循环。
如果要跳过空白值,无论是否有字体大小更改,您都应该跳过类型为Row
的单元格。从CELL_TYPE_BLANK
声明中删除该案例。