原 easyexcel(十九):导出excel实现表头和内容居中显示
版权声明:本文为博主原创文章,请尊重他人的劳动成果,转载请附上原文出处链接和本声明。
本文链接:https://www.91mszl.com/zhangwuji/article/details/1462
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>3.3.1</version>
</dependency>
/**
* 功能:easyexcel导出excel实现表头和内容居中显示
* 来源:https://91mszl.com
* @Author: zxb
* @Date: 2023-12-09 11:38:26
*/
@GetMapping("/download")
public void download(HttpServletResponse response) throws IOException {
String fileName = System.currentTimeMillis() + ".xlsx";
response.reset();
response.addHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
OutputStream os=response.getOutputStream();
List<UserInfo> dataList=new ArrayList<>();
UserInfo u1=new UserInfo();
u1.setName("张无忌");
u1.setAge(18);
u1.setAddress("上海市青浦区虹桥国际机场1号");
UserInfo u2=new UserInfo();
u2.setName("赵敏");
u2.setAge(20);
u2.setAddress("上海市黄浦区东方明珠大厦100号");
dataList.add(u1);
dataList.add(u2);
List<List<String>> headList=new ArrayList<>();
headList.add(Lists.newArrayList("姓名"));
headList.add(Lists.newArrayList("年龄"));
headList.add(Lists.newArrayList("地址"));
EasyExcel.write(os).head(headList).sheet("用户信息").registerWriteHandler(setStyleStrategy()).doWrite(dataList);
}
public HorizontalCellStyleStrategy setStyleStrategy() {
// 头的策略
WriteCellStyle headWriteCellStyle = new WriteCellStyle();
// 内容的策略
WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
// 设置 垂直居中
contentWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
// 设置 水平居中
contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
// 这个策略是 头是头的样式 内容是内容的样式 其他的策略可以自己实现
HorizontalCellStyleStrategy horizontalCellStyleStrategy = new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);
return horizontalCellStyleStrategy;
}
2023-12-09 19:05:41 阅读(463)
名师出品,必属精品 https://www.91mszl.com
博主信息