In some previous posts we have seen how we can create excel and also add various fonts to the excel file using Apache POI.
Now we will see how to Fill Color in Excel using Apache POI.
For giving a cell background color we use the following
1 2 3 |
CellStyle style = workbook.createCellStyle(); style.setFillForegroundColor(IndexedColors.BLUE.getIndex()); style.setFillPattern(CellStyle.SOLID_FOREGROUND); |
Lets see the complete code. In this code we will use 2 different cells, so that we can see difference of the fill patterns.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 |
package com.kscodes.sampleproject; import java.io.File; import java.io.FileOutputStream; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.usermodel.IndexedColors; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; public class WriteExcelUsingPOI { public static void main(String[] args) { // Create instance of the class and call the writeExcelFile() WriteExcelUsingPOI writeExcelUsingPOI = new WriteExcelUsingPOI(); writeExcelUsingPOI.writeExcelFile("C:\\kscodes\\ExcelFillTest.xlsx"); } public void writeExcelFile(String fileName) { XSSFWorkbook workbook = null; FileOutputStream fileOutputStream = null; try { fileOutputStream = new FileOutputStream(new File(fileName)); // Create a Workbook workbook = new XSSFWorkbook(); // Create an Empty Sheet XSSFSheet sheet = workbook.createSheet("FillTest"); Row row = sheet.createRow(1); Cell cell = row.createCell((short) 1); cell.setCellValue("Test the Fill - kscodes"); CellStyle style = workbook.createCellStyle(); style.setFillForegroundColor(IndexedColors.BLUE.getIndex()); style.setFillPattern(CellStyle.SOLID_FOREGROUND); cell.setCellStyle(style); cell = row.createCell((short) 3); cell.setCellValue("Test the Color - kscodes"); style = workbook.createCellStyle(); style.setFillForegroundColor(IndexedColors.YELLOW.getIndex()); style.setFillPattern(CellStyle.BRICKS); cell.setCellStyle(style); workbook.write(fileOutputStream); System.out.println("Excel File created and written !!!!"); } catch (Exception e) { System.out.println("An Exception occured while writing Excel" + e); } finally { try { if (fileOutputStream != null) { fileOutputStream.close(); } if (workbook != null) { workbook.close(); } } catch (Exception e) { } } } } |
Output