
如何在 java 中设置 excel 单元格背景色?
在 java 中使用 apache poi 库,可以轻松地为 excel 单元格设置背景色。具体步骤如下:
-
添加 poi 依赖项:在 maven 项目的 pom.xml 文件中添加以下内容:
org.apache.poi poi 5.0.0 org.apache.poi poi-ooxml 5.0.0 -
设置背景色:使用以下代码为单元格设置背景色:
立即学习“Java免费学习笔记(深入)”;
xssfcellstyle style = workbook.createcellstyle(); style.setfillforegroundcolor(hssfcolor.hssfcolorpredefined.blue.getindex()); style.setfillpattern(fillpatterntype.solid_foreground);
其中:
- style 为要设置背景色的单元格样式。
- setfillforegroundcolor() 方法设置填充色。
- setfillpattern() 方法设置填充模式,即设置为实色填充。
-
设置字体颜色:您可以通过以下代码设置单元格的字体颜色:
font font = workbook.createfont(); font.setcolor(indexedcolors.white.getindex()); style.setfont(font);
其中:
- font 为要设置字体颜色的字体。
- setcolor() 方法设置字体颜色。
示例代码:
public class Main {
public static void main(String[] args) {
try (XSSFWorkbook workbook = new XSSFWorkbook();
OutputStream out = Files.newOutputStream(Paths.get("workbook.xlsx"))) {
Sheet sheet = workbook.createSheet();
Row row = sheet.createRow((short) 0);
Cell cell = row.createCell((short) 0);
cell.setCellValue("TEST---");
// 创建一个单元格样式
XSSFCellStyle style = workbook.createCellStyle();
cell.setCellStyle(style);
// 为单元格设置蓝色背景
style.setFillForegroundColor(HSSFColor.HSSFColorPredefined.BLUE.getIndex());
style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
// 为字体设置白色
Font font = workbook.createFont();
font.setColor(IndexedColors.WHITE.getIndex());
style.setFont(font);
workbook.write(out);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}










