【发布时间】:2015-06-25 05:22:16
【问题描述】:
我已经使用 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;
}
【问题讨论】:
标签: java excel apache apache-poi