【问题标题】:Java apache poi: excel cell colorJava apache poi:excel单元格颜色
【发布时间】:2017-10-09 06:01:38
【问题描述】:

我正在尝试使用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 上,这将根据颜色打印全黑单元格或普通白色背景单元格。 我尝试了几种颜色和样式,似乎没有用。文字始终存在,但背景不适用。

伙计们,我做错了什么?

【问题讨论】:

    标签: java excel apache colors javadoc


    【解决方案1】:

    看起来像错误,但您可以尝试设置背景颜色而不是背景颜色。

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

    这将设置您的背景颜色。

    【讨论】:

    • 你是对的......确实如此!对不起,我没想到 .setFillForegroundColor 会设置背景......谈论自我解释的方法名称......我希望这只是一个错误!
    【解决方案2】:

    你忘了添加

    cell.setCellStyle(style);
    

    希望对你有帮助)

    【讨论】:

    • 现在已将其添加到 mcve。我忘了在那里复制它,但在我的主代码中我确实有它,但它不起作用。有什么想法吗?
    【解决方案3】:
    XSSFWorkbook workbook1 = new XSSFWorkbook();
    XSSFCellStyle greyBackgroundBold = workbook1.createCellStyle();
    greyBackgroundBold.setFont(font);
    greyBackgroundBold.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);
    greyBackgroundBold.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-16
      • 2017-02-01
      • 2011-08-06
      • 1970-01-01
      • 2013-11-12
      • 2017-09-11
      相关资源
      最近更新 更多