![](/img/trans.png)
[英]Read a Color from a Blank Cell in Excel to Java using Apache POI
[英]Java apache poi: excel cell color
我正试图用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
:
现在,在最新版本的Excel上 ,这将打印全黑色单元格或普通白色背景单元格,具体取决于颜色。 我尝试了几种颜色和款式,似乎没有用。 文本始终存在,但背景不适用。
我在这里做错了什么?
看起来像bug,但你可以尝试设置forground颜色而不是背景颜色。
XSSFCellStyle style = workbook.createCellStyle();
style.setFillForegroundColor(IndexedColors.RED.getIndex());
style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
row.getCell(0).setCellStyle(style);
这将设置您的背景颜色。
你忘了添加
cell.setCellStyle(style);
希望能帮助到你)
XSSFWorkbook workbook1 = new XSSFWorkbook();
XSSFCellStyle greyBackgroundBold = workbook1.createCellStyle();
greyBackgroundBold.setFont(font);
greyBackgroundBold.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);
greyBackgroundBold.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.