根据业务需求,导出excel需要隔行变色,使用pom如下
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.15</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.15</version>
</dependency>
直接使用行样式的方法是不行的 row1.setRowStyle(style),只能将一行没有数据的空白格变色,有数据的单元格不会受影响
public static void writeExcelStyle(HttpServletResponse response, List<String> header, List<List<String>> datas) {
Workbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet("Sheet1");
Row row = sheet.createRow(0);
for (int i = 0; i < header.size(); i++) {
row.createCell(i).setCellValue(header.get(i));
}
for (int i = 0; i < datas.size(); i++) {
Row row1 = sheet.createRow(i + 1);
if (i%2 != 0){
CellStyle style = workbook.createCellStyle();
style.setFillForegroundColor(IndexedColors.YELLOW.getIndex());
style.setFillPattern(CellStyle.SOLID_FOREGROUND);
row1.setRowStyle(style);
}
List<String> data = datas.get(i);
// 创建单元格设值
for (int j = 0; j < data.size(); j++) {
Cell cell = row1.createCell(j);
cell.setCellValue(data.get(j));
}
}
buildExcelDocument("File.xlsx", workbook, response);
}
修改代码,改为单元格样式 cell.setCellStyle(style):单独为每个单元格设置背景颜色
for (int i = 0; i < datas.size(); i++) {
Row row1 = sheet.createRow(i + 1);
row1.setHeightInPoints(20);
List<String> data = datas.get(i);
// 创建单元格设值
for (int j = 0; j < data.size(); j++) {
Cell cell = row1.createCell(j);
cell.setCellValue(data.get(j));
if (i%2 != 0){
CellStyle style = workbook.createCellStyle();
style.setFillForegroundColor(IndexedColors.YELLOW.getIndex());
style.setFillPattern(CellStyle.SOLID_FOREGROUND);
cell.setCellStyle(style);
}
}
}
最后切记一定要用 style.setFillForegroundColor,而不是 style.setFillBackgroundColor(),两者长得相似,且后者的字面意思更贴近“背景颜色”。