在一行中设置每个表格单元格的颜色

我有一个servlet正在接收一组数据,处理它,并根据表单提交将其写入excel文件或文本页面。 在处理Excel时,所有处理都在使用Apache POI的相应模型中进行。 我试图修改这个,以便根据包含的数据对行进行颜色编码,但是,在将颜色应用到行后,当我将工作簿写入到fileoutputstream时,颜色不在那里。 我正在处理数据到excel文件中,如下所示:

MCVE

package mcve; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.LinkedHashMap; import java.util.Set; import org.apache.poi.ss.usermodel.IndexedColors; import org.apache.poi.xssf.usermodel.XSSFCell; import org.apache.poi.xssf.usermodel.XSSFCellStyle; import org.apache.poi.xssf.usermodel.XSSFRow; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; public class MCVE { /** * @param args the command line arguments */ public static void main(String[] args) throws FileNotFoundException, IOException { LinkedHashMap<Integer, String> testReport = new LinkedHashMap<>(); testReport.put(0, "CPU"); testReport.put(1, "App"); testReport.put(2, "Other"); testReport.put(3, "Memory"); testReport.put(4, "Power"); testReport.put(5, "Disk"); File file = new File("C:/SplunkTesting/report.xlsx"); FileOutputStream out = new FileOutputStream(file); writeToExcel(testReport).write(out); out.flush(); out.close(); } private static XSSFWorkbook writeToExcel(LinkedHashMap<Integer, String> formattedReport) { try { XSSFWorkbook workbook = new XSSFWorkbook(); XSSFSheet sheet = workbook.createSheet(); int rowIndex = sheet.getLastRowNum(); Set<Integer> keySet = formattedReport.keySet(); for (Integer key : keySet) { XSSFRow row = sheet.createRow(rowIndex++); String line = formattedReport.get(key); String[] strArr = line.split(","); int cellCount = 0; for (String str : strArr) { XSSFCell cell = row.createCell(cellCount++); cell.setCellValue(str); } XSSFCellStyle style = workbook.createCellStyle(); if (line.contains("App")) { style.setFillForegroundColor(IndexedColors.BLUE.getIndex()); } else if (line.contains("CPU")) { style.setFillForegroundColor(IndexedColors.GREEN.getIndex()); } else if (line.contains("Disk")) { style.setFillForegroundColor(IndexedColors.GOLD.getIndex()); } else if (line.contains("Memory")) { style.setFillForegroundColor(IndexedColors.INDIGO.getIndex()); } else if (line.contains("Network")) { style.setFillForegroundColor(IndexedColors.LAVENDER.getIndex()); } else if (line.contains("Power")) { style.setFillForegroundColor(IndexedColors.MAROON.getIndex()); } else { style.setFillForegroundColor(IndexedColors.WHITE.getIndex()); } style.setFillPattern(XSSFCellStyle.SOLID_FOREGROUND); row.setRowStyle(style); } return workbook; } catch (Exception e) { e.printStackTrace(); } return null; } } 

我仍然得到excel文件,但格式不存在。 我究竟做错了什么?

我的解决scheme是在单元格创build和值设置循环中设置样式。 否则,每个单元格创build时会覆盖行格式,这就是为什么它是我的失败。 即使您在单元格创build后设置了行格式,情况也是如此。