【发布时间】:2021-07-02 19:55:31
【问题描述】:
在Java,如何动态处理excel表格中的空白单元格和空白列调整。
我在单元格迭代器和空白单元格类型方面遇到问题。
当我为 postgresql db 创建动态查询时,在插入查询时,由于 Excel 中的空白大小写,我遇到了异常。我正在尝试使用 poi 在空白情况下遇到异常。
try {
DataFormatter dataFormatter = new DataFormatter();
Workbook workbook = WorkbookFactory.create(excelFile);
Iterator<Sheet> sheetIterator = workbook.sheetIterator();
List<List<List<Object>>> sheets = new ArrayList<>();
while (sheetIterator.hasNext()) {
List<List<Object>> sheetList = new ArrayList<>();
Sheet sheet = sheetIterator.next();
logger.info(" ---sheet name ---" + sheet.getSheetName());
if (sheetNames != null) {
for (String sheetName : sheetNames) {
if (sheet.getSheetName().equals(sheetName)) {
Iterator<Row> rowIterator = sheet.rowIterator();
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
List<Object> rows = new ArrayList<>();
// Now let's iterate over the columns of the current row
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
CellType type = cell.getCellType();
if (type == CellType.BLANK) {
Integer intsample = 0;
cell.setCellValue(intsample);
// rows.add(dataFormatter.formatCellValue(cell));
rows.add(cell);
}
else if (type == CellType.STRING) {
rows.add(cell.getRichStringCellValue().toString());
} else if (type == CellType.NUMERIC) {
if (HSSFDateUtil.isCellDateFormatted(cell)) {
rows.add(cell.getDateCellValue());
} else if (dataFormatter.formatCellValue(cell).contains(".")) {
try {
rows.add(Double.parseDouble(dataFormatter.formatCellValue(cell)));
} catch (Exception e) {
rows.add(cell.getRichStringCellValue().toString());
}
} else {
try {
rows.add(Long.parseLong(dataFormatter.formatCellValue(cell)));
} catch (Exception e) {
rows.add(dataFormatter.formatCellValue(cell));
}
}
} else if (type == CellType.BOOLEAN) {
rows.add(cell.getBooleanCellValue());
} else {
rows.add(dataFormatter.formatCellValue(cell));
}
}
sheetList.add(rows);
}
sheets.add(sheetList);
}
}
}
}
workbook.close();
return sheets;
} catch (Exception e) {
e.printStackTrace();
}
【问题讨论】: