Java Apache POI:Excel单元格颜色

4
我正在尝试使用apache poi更改单元格的背景。

我知道有很多关于此问题的答案,但我正在使用最新版本(3.16),它们都已过时

例如,所有答案都建议我使用

CellStyle#setFillPattern(CellStyle.SOLID_FOREGROUND);

但是它已经完全过时了。

因此,根据Apache文档,我用新的函数替换了所有过时的函数,并得出了这个MCVE:

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.FillPatternType;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class Mcve{
    public static void main(String[] args) {

    //Make workbook and first sheet
    XSSFWorkbook workbook = new XSSFWorkbook();
    XSSFSheet sheet = workbook.createSheet("sheet1");

    //Make a style
    XSSFCellStyle style = workbook.createCellStyle();
    style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
    style.setFillBackgroundColor(IndexedColors.RED.getIndex());

    //Fill first line
    Row row = sheet.createRow(0);

    int i = 0;
    while (i < 5) {

        Cell cell = row.createCell(i);
        cell.setCellValue("TestCell " + i++);
                    cell.setCellStyle(style);
    }

    //Write to file
    File f = new File("Yourfilepathhere/document.xlsx"); //<-- FILL HERE

    try (FileOutputStream out = new FileOutputStream(f)) {
        workbook.write(out);
        workbook.close();
    } catch (Exception e) {
        e.printStackTrace();

    }
}
}

我建议您将其粘贴到您选择的IDE中的空Maven项目中,并请在pom.xml中添加这些依赖项:

https://pastebin.com/CXdViuW5

现在,在最新版本的Excel上,它会打印全部为黑色的单元格或正常的白色背景单元格,具体取决于颜色。 我尝试了几种颜色和样式,但好像没起作用。文本始终存在,但背景无法应用。

我在这里做错了什么呢?

3个回答

16

看起来像是一个 bug,但你可以尝试设置前景色而不是背景色。

 XSSFCellStyle style = workbook.createCellStyle();
 style.setFillForegroundColor(IndexedColors.RED.getIndex());
 style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
 row.getCell(0).setCellStyle(style);

这将设置您的背景颜色。


1
你说得对,它确实是这样!对不起,我没想到.setFillForegroundColor会设置背景……说到自解释的方法名,我希望这只是一个bug! - Lory A

0
XSSFWorkbook workbook1 = new XSSFWorkbook();
XSSFCellStyle greyBackgroundBold = workbook1.createCellStyle();
greyBackgroundBold.setFont(font);
greyBackgroundBold.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);
greyBackgroundBold.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);

0
你忘记添加了

cell.setCellStyle(style);

希望这有所帮助。

现在已将其添加到了 MCVE 中。我忘记复制它,但在我的主要代码中,我确实有它,但它不起作用。有什么想法吗? - Lory A

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接