悠悠楠杉
网站页面
正文:
在企业级应用中,Excel报表的样式设计直接影响数据可读性和用户体验。通过Java代码动态控制Excel样式,可以避免手动调整的繁琐,尤其适用于批量生成标准化报表的场景。以下是基于Apache POI库的完整实现方案。
首先引入Apache POI依赖(Maven配置):
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>5.2.3</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>5.2.3</version>
</dependency>
Workbook workbook = new XSSFWorkbook(); // 创建XLSX文件
Sheet sheet = workbook.createSheet("数据报表");
CellStyle headerStyle = workbook.createCellStyle(); // 样式对象
setFillForegroundColor和setFillPattern实现:
headerStyle.setFillForegroundColor(IndexedColors.SKY_BLUE.getIndex());
headerStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
Font font = workbook.createFont();
font.setBold(true);
font.setFontName("微软雅黑");
font.setColor(IndexedColors.WHITE.getIndex());
headerStyle.setFont(font);
headerStyle.setBorderTop(BorderStyle.THIN);
headerStyle.setBorderBottom(BorderStyle.DOUBLE);
headerStyle.setBorderLeft(BorderStyle.THIN);
headerStyle.setBorderRight(BorderStyle.THIN);
以下代码演示如何为表头和数据行应用不同样式:
// 设置表头行
Row headerRow = sheet.createRow(0);
String[] headers = {"姓名", "部门", "销售额"};
for (int i = 0; i < headers.length; i++) {
Cell cell = headerRow.createCell(i);
cell.setCellValue(headers[i]);
cell.setCellStyle(headerStyle); // 应用样式
}
// 设置数据行样式
CellStyle dataStyle = workbook.createCellStyle();
dataStyle.setWrapText(true); // 自动换行
dataStyle.setAlignment(HorizontalAlignment.CENTER);
// 填充数据
List<String[]> data = Arrays.asList(
new String[]{"张三", "市场部", "85000"},
new String[]{"李四", "技术部", "62000"}
);
for (int rowIdx = 0; rowIdx < data.size(); rowIdx++) {
Row row = sheet.createRow(rowIdx + 1);
String[] rowData = data.get(rowIdx);
for (int colIdx = 0; colIdx < rowData.length; colIdx++) {
Cell cell = row.createCell(colIdx);
cell.setCellValue(rowData[colIdx]);
cell.setCellStyle(dataStyle);
}
}
sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 2)); // 合并首行3列
条件格式设置
通过ConditionalFormattingRule实现动态颜色标记(如销售额低于阈值标红)。
性能优化
- 复用CellStyle对象减少内存占用
- 使用SXSSFWorkbook处理大数据量
通过灵活组合这些方法,可以生成专业级的Excel报表,满足财务、运营等场景的复杂需求。