How to get cell style of empty cell apache POI

后端 未结 1 576
梦毁少年i
梦毁少年i 2020-12-07 04:55

I am using poi-ooxml@3.17 to read and write excel file. I have added some styles/protection on some of cells. When i read the file i am not able to get cell styles applied t

相关标签:
1条回答
  • 2020-12-07 05:31

    Cells without content or explicit style applied are not present in the sheet because of not to increase the file size unnecessarily. So apache poi returns null for such cells.

    If you are looking at the sheet in spreadsheet application, then maybe it looks as if all cells in a row or all cells in a column have the same style applied to. But this is not the case. In real the row and/or the column has the style applied to. Only cells in intersection of styled rows and columns must be present in the sheet having the last applied style.

    If a new cell needs to be created, then the spreadsheet application gets the preferred style for that 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). Unfortunately apache poi does not do so. So we need doing this ourself:

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

    This method may be used in code every time a new cell needs to be created:

    ...
       if (Objects.isNull(cell)) {
        cell = row.createCell(colIndex);
        cell.setCellStyle(getPreferredCellStyle(cell));
       }
    ...
    
    0 讨论(0)
提交回复
热议问题