gpt4 book ai didi

java - 如何获取空单元格apache POI的单元格样式

转载 作者:行者123 更新时间:2023-11-30 02:13:47 29 4
gpt4 key购买 nike

我正在使用 poi-ooxml@3.17 读取和写入 Excel 文件。我在一些单元格上添加了一些样式/保护。当我读取文件时,我无法将单元格样式应用于没有值的单元格,因为当我尝试访问具有空值的行/单元格时,它返回 null。

下面是在同一个 Excel 文件中写入数据的代码。

public static void writeDataToSheet(final Sheet sheet, final List<Map<String, Object>> sheetData) {

List<String> columns = getColumnNames(sheet);
LOGGER.debug("Inside XLSXHelper writeDataToSheet {}", Arrays.asList(columns));
IntStream.range(0, sheetData.size()).forEach((index) -> {
if (Objects.isNull(sheet.getRow(index + 1))) {
sheet.createRow(index + 1);
}
Row row = sheet.getRow(index + 1);
Map<String, Object> data = sheetData.get(index);
IntStream.range(0, columns.size()).forEach((colIndex) -> {
String column = columns.get(colIndex);

Cell cell = row.getCell(colIndex);
if (Objects.isNull(cell)) {
cell = row.createCell(colIndex);
}
cell.setCellValue(data.get(column) != null ? data.get(column).toString() : null);
});
});
}

任何人都可以为我提供一个解决方案,让我可以在单元格为空时读取应用于单元格的样式吗?

谢谢。

最佳答案

没有内容或应用显式样式的单元格不会出现在工作表中,因为不会不必要地增加文件大小。因此,apache poi 对于此类单元返回 null

如果您在电子表格应用程序中查看工作表,那么可能看起来行中的所有单元格或列中的所有单元格都应用了相同的样式。但这种情况并非如此。实际上,行和/或列已应用样式。只有样式行和列交叉处的单元格必须出现在具有上次应用样式的工作表中。

如果需要创建新单元格,电子表格应用程序将获取该单元格的首选样式。这是已应用的单元格样式,如果不存在,则为行样式(该行的默认单元格样式);如果不存在,则为列样式(该列的默认单元格样式)。不幸的是 apache poi 并没有这样做。所以我们需要自己做这件事:

 public CellStyle getPreferredCellStyle(Cell cell) {
// a method to get the preferred cell style for a cell
// this is either the already applied cell style
// or if that not present, then the row style (default cell style for this row)
// or if that not present, then the column style (default cell style for this column)
CellStyle cellStyle = cell.getCellStyle();
if (cellStyle.getIndex() == 0) cellStyle = cell.getRow().getRowStyle();
if (cellStyle == null) cellStyle = cell.getSheet().getColumnStyle(cell.getColumnIndex());
if (cellStyle == null) cellStyle = cell.getCellStyle();
return cellStyle;
}

每次需要创建新单元格时,都可以在代码中使用此方法:

...
if (Objects.isNull(cell)) {
cell = row.createCell(colIndex);
cell.setCellStyle(getPreferredCellStyle(cell));
}
...

关于java - 如何获取空单元格apache POI的单元格样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49270297/

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