返回

一键掌握Java设置Excel单元格样式!全面指南来了

后端

如何在 Java 中使用 CellStyle 属性设置 Excel 单元格样式

背景颜色

我们使用 CellStyle.setFillBackgroundColor() 方法为单元格设置背景色。我们可以使用颜色名称(如 "red")或十六进制颜色代码(如 "#FF0000")。

CellStyle cellStyle = workbook.createCellStyle();
cellStyle.setFillBackgroundColor(IndexedColors.RED.getIndex());

字体

使用 CellStyle.setFont() 方法设置单元格的字体。我们可以指定字体名称(如 "Arial")、大小和颜色。

CellStyle cellStyle = workbook.createCellStyle();
Font font = workbook.createFont();
font.setFontName("Arial");
font.setFontHeightInPoints((short) 10);
font.setColor(IndexedColors.BLUE.getIndex());
cellStyle.setFont(font);

边框

通过 CellStyle.setBorder() 方法设置单元格边框。我们可以指定边框类型(如 "BORDER_THIN")和颜色。

CellStyle cellStyle = workbook.createCellStyle();
cellStyle.setBorder(BorderStyle.THIN, IndexedColors.BLACK.getIndex());

对齐方式

使用 CellStyle.setAlignment() 方法设置单元格对齐方式。我们可以指定水平对齐方式(如 "ALIGN_CENTER")和垂直对齐方式(如 "ALIGN_TOP")。

CellStyle cellStyle = workbook.createCellStyle();
cellStyle.setAlignment(HorizontalAlignment.CENTER);
cellStyle.setVerticalAlignment(VerticalAlignment.TOP);

其他样式

除了上述基本样式外,我们还可以使用 CellStyle 属性设置其他样式,例如数字格式、数据验证和单元格保护。

CellStyle cellStyle = workbook.createCellStyle();
cellStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("0.00"));
cellStyle.setLocked(true);

结论

通过使用 CellStyle 属性,我们可以在 Excel 中为单元格设置各种样式。这些样式可以增强可读性、组织性以及我们工作簿的整体外观。

常见问题解答

  • 如何设置单元格为粗体?

    • font.setBold(true)
  • 如何设置单元格底纹?

    • cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND)
  • 如何创建单元格下拉列表?

    • 使用 DataValidation
  • 如何应用样式到多个单元格?

    • sheet.setDefaultColumnStyle(0, cellStyle)
  • 如何复制单元格样式?

    • cellStyle.cloneStyleFrom(existingCellStyle)