需求:
- 首行字体单独设置,背景颜色按指定需求输出
- 2.不同列限制不同字数,字数达到限制数后,要求自动换行输出
主要代码参考如下:
如果涉及大量请求,需要单独做异步处理
@RequestMapping("export")
@ResponseBody
public void export(HttpServletResponse response) {
try (
//不适于大量数据情况
ExcelWriter writer = ExcelUtil.getWriter();
ServletOutputStream out = response.getOutputStream();
HSSFWorkbook hssfworkbook = (HSSFWorkbook) writer.getWorkbook();
) {
List<User> list = new ArrayList<>();
list.add(new User("zhangsanddddddddddddddddddddddddddddddddddddddddddddddddd", "1231", new Date()));
list.add(new User("zhangsan1ddddddddddddddddddddddddddddddd", "1232", new Date()));
list.add(new User("zhangsan2dddddddddddddddddd", "1233", new Date()));
list.add(new User("zhangsan3", "1234", new Date()));
list.add(new User("zhangsan4", "1235", new Date()));
list.add(new User("zhangsan5", "1236", DateUtil.date(new Date())));
//自定义单元格样式,获取头部样式编辑
CellStyle headCellStyle = writer.getHeadCellStyle();
//预定义填充样式
headCellStyle.setFillForegroundColor(HSSFColor.HSSFColorPredefined.LIME.getIndex());
//拿到palette颜色板
HSSFPalette palette = hssfworkbook.getCustomPalette();
//把预填充的HSSFColor.HSSFColorPredefined.LIME.getIndex()替换为期望RGB颜色
palette.setColorAtIndex(HSSFColor.HSSFColorPredefined.LIME.getIndex(), (byte) 192, (byte) 0, (byte) 0);
Font font = writer.createFont();
font.setColor(IndexedColors.WHITE.getIndex());
font.setBold(true);
//设置字体
font.setFontName("微软雅黑");
headCellStyle.setFont(font);
//设置对应列间距,不设置默认10,即最终达到9个字符时会自动换行
writer.setColumnWidth(0, 40);
writer.setColumnWidth(1, 20);
writer.setColumnWidth(2, 30);
writer.setColumnWidth(3, 40);
//设置所有单元格超过设置列间距自动换行
StyleSet ss = writer.getStyleSet();
ss.setWrapText();
writer.setStyleSet(ss);
//自定义标题别名,可能因为版本导致顺序问题,如果需要加别名,建议所有字段都加上别名
writer.addHeaderAlias("name", "姓名");
writer.addHeaderAlias("age", "年龄");
writer.addHeaderAlias("birthday", "生日");
// 合并单元格后的标题行,使用默认标题样式
//writer.merge(2, "自定义标题");
// 一次性写出内容,使用默认样式,强制输出标题
writer.write(list, true);
//out为OutputStream,需要写出到的目标流
//response为HttpServletResponse对象
response.setContentType("application/vnd.ms-excel;charset=utf-8");
//需要转码
String name = "测试11UTF-8";
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(name, "UTF-8") + ".xls");
writer.flush(out, true);
} catch (IOException e) {
e.printStackTrace();
}
}
pom
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.4.5</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.2</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>3.17</version>
</dependency>
导出后结果

参考:
https://blog.csdn.net/AlbenXie/article/details/109712434
https://www.coder.work/article/4682438
网友评论