Shi*_*ish 2 java excel apache-poi
我正在使用 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);
});
});
}
Run Code Online (Sandbox Code Playgroud)
谁能给我提供一个解决方案,让我可以在单元格为空时读取应用于单元格的样式?
谢谢。
没有内容或应用显式样式的单元格不会出现在工作表中,因为不会不必要地增加文件大小。因此此类细胞的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;
}
Run Code Online (Sandbox Code Playgroud)
每次需要创建新单元时,可以在代码中使用此方法:
...
if (Objects.isNull(cell)) {
cell = row.createCell(colIndex);
cell.setCellStyle(getPreferredCellStyle(cell));
}
...
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5093 次 |
| 最近记录: |