Excel cell color not being set via java

44 Views Asked by At

I am trying to create an excel workbook via Java, and set a cell to green. Everything works fine. It creates the book, enters the text and I can open it from explorer. However, the background color does not get set to green. I looked via Google and used the example they showed. Here is part of the code (only the important parts):

 static String Title = "This is the title";
 ...
 public static void createExcelFile(String templateFile, String fileName, String tin, String first, String last,
        String dos, String billed, String dob) throws KDTException {
      ...
      String title = Title;
      ...
      for (int rn = 0; rn < rowsList.size(); rn++) {
        List<String> rowData = rowsList.get(rn);
        XSSFRow row = sheet.createRow((short) rn);
        for (int cn = 0; cn < rowData.size(); cn++) {
            String val = rowData.get(cn);
            XSSFCell theCell = row.createCell(cn);
            theCell.setCellValue(val);
            if (val.equals(title)) {
                XSSFCellStyle sty = theCell.getCellStyle();
                sty.setFillBackgroundColor(new XSSFColor(java.awt.Color.GREEN));
                theCell.setCellStyle(sty);
                theCell.setCellValue(val);
            }
        }
    }
 }

But the cell is not green (see picture)enter image description here

(that green box is just the cell that the cursor currently selected, not the background color). I have stepped through to be sure the code was getting executed inside the check for val, and it is. And I use the XSSFWorkbook-related calsses (which I believe makes .xlsx instead of .xls).

Any idea what I am missing? Do I have to do some sort of perform() call, like in Actions?

1

There are 1 best solutions below

1
On

You are missing the Fill Pattern. See: How to set background color of a cell using apache poi 4.1.0

FillPatternType fillPattern = cellStyle.getFillPattern();
System.out.println(fillPattern); <-- yours will be NO_FILL
cellStyle.setFillForegroundColor(IndexedColors.LEMON_CHIFFON.index);
cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);