gpt4 book ai didi

java - 我在 Excel 工作表中的单元格迭代器和空白单元格类型方面面临问题。如何动态处理空白单元格和空白列调整

转载 作者:行者123 更新时间:2023-12-01 22:29:09 24 4
gpt4 key购买 nike

Java中,如何动态处理Excel工作表中的空白单元格和空白列调整。

我在单元格迭代器和空白单元格类型方面遇到问题。

当我为 postgresql db 创建动态查询时,在插入查询时,由于 Excel 中的空白情况,我收到异常。我正在尝试使用 poi 在空白情况下出现异常。

Excel image

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();
}

最佳答案

CellIterator 在迭代一行中的单元格时会跳过空单元格。您可以通过使用 for 循环而不是迭代器来解决该问题:

Row row = rowIterator.next();
...
int lastCellIndex = 8; // (9-1 cells)
for (int i=0; i<=lastCellIndex; i++) {
Cell cell = row.getCell(cn, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
...
}

在您的示例中,单元格数量为 9,使得 lastCellIndex 为 8。如果一行中的单元格数量有所不同,请在顶部标题行上使用 row.getLastCellNum(); 来接收长度。

有关 getCell() 的更多信息可以在 documentation 中找到。 .

关于java - 我在 Excel 工作表中的单元格迭代器和空白单元格类型方面面临问题。如何动态处理空白单元格和空白列调整,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58556611/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com