I tried to use setFillForegroundColor and setFillBackgroundColor to change the cell color of an excel file.
However, I failed and I really didn't know what the problem was. I've googled for many hours and still couldn't find the right way to set the color.
The following is the code I write:
import java.awt.Color;
import java.io.File;
import java.io.FileOutputStream;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFColor;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class TestColor {
public static void main(String[] args) {
File f = new File("test.xlsx");
XSSFWorkbook wb = new XSSFWorkbook();
XSSFSheet sheet = wb.createSheet();
XSSFRow row = sheet.createRow(0);
XSSFCell cell = row.createCell(0);
cell.setCellValue("no blue");
// set the color of the cell
XSSFCellStyle style = wb.createCellStyle();
XSSFColor myColor = new XSSFColor(Color.BLUE);
style.setFillForegroundColor(myColor);
style.setFillBackgroundColor(myColor);
cell.setCellStyle(style); // this command seems to fail
try {
FileOutputStream fos = new FileOutputStream(f);
wb.write(fos);
wb.close();
fos.flush();
fos.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
And this is the final result.
How can I set the cell's color to blue?
I'm using poi-bin-3.12-20150511.zip from https://poi.apache.org/download.html
You may need to add the following line after setting the foreground colour:
style.setFillPattern(CellStyle.SOLID_FOREGROUND);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With