2

I try to use Apache POI to change background colors of cells in a row. I use following code to handle it in xls file, but there aren't any changes in file after execution.

FileInputStream fis = new FileInputStream(src);
HSSFWorkbook wb = new HSSFWorkbook(fis);                
r = sheet.getRow(5);
CellStyle style = wb.createCellStyle();
style.setFillForegroundColor(IndexedColors.RED.getIndex());
r.setRowStyle(style);
plaidshirt
  • 5,189
  • 19
  • 91
  • 181
  • 1
    That code doesn't alter the file itself in any way. Is that all the code? – XtremeBaumer Mar 21 '19 at 13:29
  • @XtremeBaumer : I just added following lines after these, but style is not present in xls. `FileOutputStream fileOut = new FileOutputStream(excelFileName); wb.write(fileOut);` – plaidshirt Mar 21 '19 at 13:49
  • Also call `wb.close();` and `fileOut.close();` jsut to be sure (unless you use `try-with-resource`). BTW, how do you get `sheet`? You create a new `HSSFWorkbook` but never call `wb.getSheet()` or `wb.createSheet()` – XtremeBaumer Mar 21 '19 at 14:11
  • @XtremeBaumer : I use this, sorry, I didn't paste it: `HSSFSheet sheet = wb.getSheetAt(0);` – plaidshirt Mar 21 '19 at 14:15
  • 1
    Update the question with the full code – XtremeBaumer Mar 21 '19 at 14:16
  • I think you just need to include `style.setFillPattern(FillPatternType.SOLID_FOREGROUND);` before applying the style – XtremeBaumer Mar 21 '19 at 14:17
  • @XtremeBaumer : This helped, but red background applied only on part of the cells in this row, so isn't from column A. – plaidshirt Mar 21 '19 at 14:39
  • If you call `r.createCell(0);` after `r.setRowStyle(style);` it will overwrite the row style for that cell. It might be worth it to try to set the `rowstyle` after you finished creating new cells in the row – XtremeBaumer Mar 21 '19 at 14:55
  • @XtremeBaumer : I do these changes on an existing xls file, so cells are created. – plaidshirt Mar 22 '19 at 20:31

1 Answers1

4

Style for cells has to be defined like this.

HSSFCellStyle tCs = wb.createCellStyle();
tCs.setFillPattern(FillPatternType.SOLID_FOREGROUND);
tCs.setFillForegroundColor(IndexedColors.YELLOW.getIndex());

It has to be applied each cells, which needed this style.

for (int k = 0; k < sheet.getRow(5).getLastCellNum(); k++) {
   sheet.getRow(i).getCell(k).setCellStyle(tCs);
}
plaidshirt
  • 5,189
  • 19
  • 91
  • 181