【问题标题】:How to apply background color for the rows in excel sheet using Apache POI?如何使用 Apache POI 为 Excel 工作表中的行应用背景颜色?
【发布时间】:2011-09-07 13:41:44
【问题描述】:

我正在使用 Apache POI 将数据导出到 Excel 工作表中。它工作正常。问题是我需要在生成 excel 表时为 excel 表中的几行应用黄色背景色。请教我如何在生成时为 excel 表的行应用背景颜色。

谢谢, 雷迪

【问题讨论】:

标签: java apache-poi


【解决方案1】:

直接来自official guide:

    // Aqua background
CellStyle style = wb.createCellStyle();
style.setFillBackgroundColor(IndexedColors.AQUA.getIndex());
style.setFillPattern(CellStyle.BIG_SPOTS);
row.setRowStyle(style);

【讨论】:

  • @karla 效果很好。但是,如果我将绿色应用于其他行,即如果我将黄色应用于第 2 行,将绿色应用于第 5 行,则第 2 行最终变为绿色。任何想法
  • 但是,当我在行中创建单元格而不对这些单元格应用此样式或任何其他样式时,它们没有行样式。看来我也必须将样式添加到单元格中。
  • 一些修正style.setFillPattern(FillPatternType.BIG_SPOTS);
【解决方案2】:
//Opening excel file
FileInputStream inputStream = new FileInputStream(new File(excelFileLocation));
XSSFWorkbook resultWorkbook = new XSSFWorkbook(inputStream);
XSSFSheet resultSheet = resultWorkbook.getSheet(sheetName);
//Applying style
XSSFRow sheetrow = resultSheet.getRow(1); // Row number     
XSSFCellStyle style = resultWorkbook.createCellStyle();
style.setFillForegroundColor(IndexedColors.GREEN.getIndex());
style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
sheetrow.getCell(0).setCellStyle(style);//Cell number            

//Saving file       
FileOutputStream outFile =new FileOutputStream(new File(excelFile));
resultWorkbook.write(outFile);
outFile.close();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-16
    相关资源
    最近更新 更多