表格文件使用POI下载,表头样式设置
下载表格文件时不知道怎么在后台设置表格的样式,以及表的内容的字体大小样式等?
带你看看这个注解,你一定喜欢
首先前台的点击下载按钮
点击后页面效果是这样滴
导出的数据表长这个样子
1.前台代码这个样子
<a-button style="margin-left: 8px" @click="exportExcel">
<a-icon type="export" />导出
</a-button>
省略号。。。
exportExcel () {
let fileName = '导出文件名_' + moment().format('YYYYMMDDHHmmss') + '.xlsx'
this.$download('/poiExcel', {
...this.queryParams //要导出数据的查询条件参数
}, name)
}
点击导出按钮,触发事件,调用后台接口
2.后台数据是这样滴
首先是实体类
@Data//自动生成set get方法
@HeadFontStyle(fontHeightInPoints = 12,fontName="微软雅黑") //头字体设置大小颜色
@ContentFontStyle(fontHeightInPoints = 11,fontName="微软雅黑")//内容设置字体大小颜色
@ContentStyle(borderLeft = BorderStyle.DASHED,borderRight = BorderStyle.DASHED,borderTop = BorderStyle.DASHED,borderBottom = BorderStyle.DASHED)//内容表格样式
public class Person{
@ExcelIgnore //添加进表格中时,忽略掉该数据
private Long id;//id
@ColumnWidth(20)//指定列宽度
@ExcelProperty("姓名") //标题
private String name;
@ColumnWidth(20)
@ExcelProperty("年龄")
private String age;
@ColumnWidth(20)
@ExcelProperty("手机号")
private String cell;
}
然后是接口
@RequestMapping(value = "/poiExcel" ,method = RequestMethod.POST)
public void poiExcel(Person p, HttpServletResponse response) throws IOException {
try {
// List<Person > list = Person Service.getPerson List(p);//根据条件查询数据
ArrayList<Person > list = new ArrayList<>();
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.setCharacterEncoding("utf-8");
// 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
String fileName = URLEncoder.encode("人员统计表" + DateUtil.formatFullTime(LocalDateTime.now()), "UTF-8").replaceAll("\\+", "%20");
response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
// 这里需要设置不关闭流
// ExcelWriterBuilder
EasyExcel.write(response.getOutputStream(), Person .class)//生成表头(应用反射)
.autoCloseStream(false)//是否自动关闭输入流
.sheet("数据").doWrite(list);//读取所有数据
} catch (Exception e) {
// 重置response
response.reset();
response.setContentType("application/json");
response.setCharacterEncoding("utf-8");
Map<String, String> map = new HashMap<String, String>();
map.put("status", "failure");
map.put("message", "导出文件失败" + e.getMessage());
response.getWriter().println(JSON.toJSONString(map));
}
}