1

In the below code, I want to set the color in style.setFillForegroundColor(IndexedColors.GREEN.getIndex()) dynamically but here the color is set statically.

Suppose in Frontend I have color picker and I choose to set the color into it and passed the color in JSON and post the JSON data through fetch API and when I get the color in @Requestbody then I want to set that color in setFillForeGroundColor().

I have searched it on Google but didn't get the result. Here is my code:

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ColorXLSX {
    public static void main(String[] args) throws IOException {
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("Color Test");
        Row row = sheet.createRow(0);

        CellStyle style = workbook.createCellStyle();
        style.setFillForegroundColor(IndexedColors.GREEN.getIndex());
        style.setFillPattern(CellStyle.SOLID_FOREGROUND);
        Font font = workbook.createFont();
            font.setColor(IndexedColors.RED.getIndex());
            style.setFont(font);

        Cell cell1 = row.createCell(0);
        cell1.setCellValue("ID");
        cell1.setCellStyle(style);

        Cell cell2 = row.createCell(1);
        cell2.setCellValue("NAME");
        cell2.setCellStyle(style);

        FileOutputStream fos =new FileOutputStream(new File("D:/xlsx/cp.xlsx"));
        workbook.write(fos);
        fos.close();
        System.out.println("Done");
    }`
``





halfer
  • 19,824
  • 17
  • 99
  • 186
  • 1
    See https://stackoverflow.com/questions/53117806/adding-custom-colours-to-excel-sheet-using-apache-poi/53120147#53120147 or https://stackoverflow.com/questions/58594849/apache-poi-4-1-set-cell-background-color-from-hex-code/58603161#58603161 – Axel Richter May 23 '20 at 12:41
  • Thanks, @AxelRichter for helping me. Let me implement this code. if I get stuck in any line of code then I will ask from you. – ankur shishodia May 23 '20 at 15:10
  • hey! @AxelRichter how do I add the indexed value to set the color of the header of different columns. In the second link you have mentioned the code to set the background color from hex-code. and what does IndexedColorMap do? – ankur shishodia May 23 '20 at 19:37
  • 1
    Multiple different questions different from your current question. This is not what comments are for. Please ask only **one** question per question block in StackOverflow. And in each question please show what you have tried, what is the outcome of what you tried and what is your expected result. – Axel Richter May 24 '20 at 04:09

0 Answers0