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

时间:2018-03-14 05:30:17

标签: 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);
        });
    });
}

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

感谢。

1 个答案:

答案 0 :(得分:1)

由于不会不必要地增加文件大小,因此工作表中不存在没有内容或显式样式的单元格。因此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));
   }
...
相关问题