我正在尝试设置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);
}
}
我在这里找到了一个类似的问题[如何使用apache pio 4.1.0设置单元格的背景颜色,但是答案没有帮助。
请问您能否指导我解决这个问题。
谢谢。
CellStyle.setFillForegroundColor
和实心图案FillPatternType.SOLID_FOREGROUND
。那么,如果您在代码中使用cellStyle.setFillForegroundColor(IndexedColors.GREY_50_PERCENT.index); cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
而不是cellStyle.setFillBackgroundColor
会发生什么? - Axel Richter