【发布时间】: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:
现在,在最新版本的 Excel 上,这将根据颜色打印全黑单元格或普通白色背景单元格。 我尝试了几种颜色和样式,似乎没有用。文字始终存在,但背景不适用。
伙计们,我做错了什么?
【问题讨论】:
标签: java excel apache colors javadoc