一、easyexcel介绍
Java解析、生成Excel比较有名的框架有Apache poi、jxl。但他们都存在一个严重的问题就是非常的耗内存,poi有一套SAX模式的API可以一定程度的解决一些内存溢出的问题,但POI还是有一些缺陷,比如07版Excel解压缩以及解压后存储都是在内存中完成的,内存消耗依然很大。easyexcel重写了poi对07版Excel的解析,能够原本一个3M的excel用POI sax依然需要100M左右内存降低到几M,并且再大的excel不会出现内存溢出,03版依赖POI的sax模式。在上层做了模型转换的封装,让使用者更加简单方便。
二、easyexcel使用
1、excel导出
通过注解设置字段属性
@Data
public class Person {
@ExcelProperty(value = {"人员信息", "姓名"}, index = 0, converter = AutoConverter.class)
private String name;
@ExcelProperty(value = {"人员信息","年龄"}, index = 1)
private int age;
@ExcelProperty(value = {"人员信息","性别"}, index = 2)
private int sex;
@ExcelProperty(value = "生日")
@DateTimeFormat("yyyy年MM月dd日HH时mm分ss秒")
private Date date;
@ExcelIgnore
private String ignore;
@ExcelProperty(value = "图片")
private URL url;
public Person(String name, int age, int sex, Date date) throws Exception {
this.name = name;
this.age = age;
this.sex = sex;
this.date = date;
this.url = new URL("https://wx2.sinaimg.cn/mw690/8345c393ly1g926qez2f9j23jk1zsnpf.jpg");
}
}
@ExcelProperty 设置字段导出的名称,列次。没有指定的列会空着。多个value复杂头。
@ExcelIgnore 忽略有此注解的字段
@DateTimeFormat 日期格式转换
@NumberFormat 数字转换
图片的导出可以用ByteArray、file、String、Stream、Url的方法进行导出
web中的写:
@RequestMapping("write")
public void writeExcel(HttpServletResponse response) throws Exception{
//模拟数据
List<Person> list = new ArrayList<Person>() {{
add(new Person("lining", 24, 1, new Date()));
add(new Person("lining", 24, 1, new Date()));
add(new Person("lining", 24, 1, new Date()));
}};
response.setContentType("application/vnd.ms-excel");
response.setCharacterEncoding("utf-8");
String fileName = URLEncoder.encode("人员信息", "UTF-8");
response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
EasyExcel.write(response.getOutputStream(), Person.class).sheet("人员").doWrite(list);
}
来源:CSDN
作者:李兮宁
链接:https://blog.csdn.net/li_xiao_ning/article/details/103946171