poi坑点(springboot)
工作上需要写了一个将数据库数据生成excel表的接口,在此过程中遇到了一些坑点,现在此纪录
PS:一部分可能是因为我没用明白
1. 样式问题
-
自动调整尽量不要使用,部分列留白过多,空列列宽过窄,可能是只自动调整了一列的缘故。
代码:
for (int index = 0; index < 14; index++){
sheet.autoSizeColumn(index);
}
效果图:
-
建议使用setCellStyle(),而不是setRowStyle()。直接使用setRowStyle()会导致只有没存入
数据的单元格设置样式成功。
代码:
Row dataRow = sheet.createRow(rowIndex);
dataRow.setRowStyle(dataStyle);
效果图:
![](https://i.imgur.com/ktbPhHX.png)
![](https://i.imgur.com/j2s6597.png)
![](https://i.imgur.com/A63oPyu.png)
- 最终成品
样式代码:
// 标题格式
Font titleFont = xssfWorkbook.createFont();
titleFont.setFontName("黑体");
titleFont.setFontHeightInPoints((short) 12);
titleFont.setBold(true);
XSSFCellStyle titleStyle = xssfWorkbook.createCellStyle();
titleStyle.setAlignment(XSSFCellStyle.ALIGN_CENTER);
titleStyle.setFont(titleFont);
titleStyle.setBorderTop(BorderStyle.THIN);//边框线
titleStyle.setBorderLeft(BorderStyle.THIN);
titleStyle.setBorderRight(BorderStyle.THIN);
titleStyle.setBorderBottom(BorderStyle.THIN);
// 数据格式
Font dataFont = xssfWorkbook.createFont();
dataFont.setFontName("宋体");
dataFont.setFontHeightInPoints((short) 11);
dataFont.setBold(false);
XSSFCellStyle dataStyle = xssfWorkbook.createCellStyle();
dataStyle.setAlignment(XSSFCellStyle.ALIGN_CENTER);
dataStyle.setFont(dataFont);
dataStyle.setBorderTop(BorderStyle.THIN);
dataStyle.setBorderLeft(BorderStyle.THIN);
dataStyle.setBorderRight(BorderStyle.THIN);
dataStyle.setBorderBottom(BorderStyle.THIN);
样式设置代码:
for (StandardColumnEntity columnDetail : columnDetailList){
Row dataRow = sheet.createRow(rowIndex);
// 业务分类
Cell categoryCell = dataRow.createCell(0);
categoryCell.setCellStyle(dataStyle);
categoryCell.setCellValue(columnInfo.getCategoryName());;
// 数据集标识
Cell tableEnNameCell = dataRow.createCell(1);
tableEnNameCell.setCellStyle(dataStyle);
tableEnNameCell.setCellValue(columnDetail.getTableEnName());
...
rowIndex++;
}
效果图:
![](https://i.imgur.com/RlGrUpl.png)
### 2. 其他问题
- 网上部分代码设置了response的header和Content-Type,但如果不做出相应接收,会报"Could not find acceptable representation"的错误
```
response.setHeader("content-Type", "application/octet-stream");//有的是application/vnd.ms-excel
response.setContentType("application/octet-stream");
喜欢《名侦探狄仁杰》里诸葛王朗的一句话:你开心也是一天,不开心也是一天,何不给自己一个大大的微笑?《冰与火之歌》说:The living should smile, for the dead cannot.(活着的人理应欢笑,因为死者无法做到)。
人生苦短,应当及时行乐,大声欢笑。