【发布时间】:2020-02-16 21:28:34
【问题描述】:
我正在尝试为 excel 文件中的标题设置背景颜色,但是在单元格上没有可见内容的黑色。我正在使用 apache poi 4.1.0 和 poi-ooxml 4.1.0。
这是我正在尝试的代码。
XSSFWorkbook workbook = new XSSFWorkbook();
// Create a blank sheet
XSSFSheet sheet = workbook.createSheet("student Details");
XSSFCellStyle cellStyle = sheet.getWorkbook().createCellStyle();
cellStyle.setFillBackgroundColor(IndexedColors.GREY_50_PERCENT.index);
cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
// This data needs to be written (Object[])
Map<String, Object[]> data = new TreeMap<String, Object[]>();
data.put("1", new Object[] { "ID", "NAME", "LASTNAME" });
data.put("2", new Object[] { 1, "Pankaj", "Kumar" });
data.put("3", new Object[] { 2, "Prakashni", "Yadav" });
data.put("4", new Object[] { 3, "Ayan", "Mondal" });
data.put("5", new Object[] { 4, "Virat", "kohli" });
// Iterate over data and write to sheet
Set<String> keyset = data.keySet();
int rownum = 0;
for (String key : keyset) {
// this creates a new row in the sheet
XSSFRow row = sheet.createRow(rownum++);
Object[] objArr = data.get(key);
int cellnum = 0;
for (Object obj : objArr) {
// this line creates a cell in the next column of that row
XSSFCell cell = row.createCell(cellnum++);
cell.setCellStyle(cellStyle);
if (obj instanceof String)
cell.setCellValue((String) obj);
else if (obj instanceof Integer)
cell.setCellValue((Integer) obj);
}
}
我在这里发现了一个类似的问题[how to set background color of a cell using apache pio 4.1.0,但答案没有帮助。
请您指导我解决这个问题。
谢谢。
【问题讨论】:
-
正如我在链接的答案中所说:单元内部使用图案填充。填充背景色是图案背后的颜色。填充前景色是图案的颜色。要使用纯色填充单元格,您需要使用填充 foreground color
CellStyle.setFillForegroundColor和 solid patternFillPatternType.SOLID_FOREGROUND。那么,如果您在cellStyle.setFillBackgroundColor的代码中使用cellStyle.setFillForegroundColor(IndexedColors.GREY_50_PERCENT.index); cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);,会发生什么情况? -
cs.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex()) cs.setFillPatternType(CellStyle.SOLID_FOREGROUND) with poi-3.14
标签: java excel apache-poi