我正在尝试使用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上,它会打印全部为黑色的单元格或正常的白色背景单元格,具体取决于颜色。 我尝试了几种颜色和样式,但好像没起作用。文本始终存在,但背景无法应用。
我在这里做错了什么呢?