需要导入EasyExcel包
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>2.2.6</version>
</dependency>
配置表格中列的信息
须在对于的类中进行注释
@ExcelIgnoreUnannotated //生产excel时忽略未注释的字段
@HeadStyle(horizontalAlignment = HorizontalAlignment.CENTER)//表头样式居中
@ContentStyle(horizontalAlignment = HorizontalAlignment.CENTER)//内容样式居中
@ColumnWidth(12)//宽度
public class User(){
//列名,位置
@ExcelProperty(value = "名字", index = 0)
@@ColumnWidth(15)
private String name;
@ExcelProperty(value = "年龄", index = 1)
private Integer age;
//没注释不显示
private String phone;
}
在controller类中
public void exportExcel(){
//数据集,存放显示的数,这里不写
List<User> users = new LinkedList<>();
//生成EXCEL
response.setContentType("application/vnd.ms-excel");
response.setCharacterEncoding("utf-8");
//设置文件名
response.setHeader("Content-Disposition", "attachment;filename=" + new Date().getTime() + ".xlsx");
EasyExcel.write(response.getOutputStream(), ComplaintOverviewDto.class).sheet("模板").doWrite(complaintOverviewDtos);
}
前端请求后会发送文件的流,如果不能下载 请将流转成文件