EasyExecl导出并录入
选用EasyExecl
最近业务中需要录入execl表格,之前项目用的都是poi,查了下资料看,poi容易引起OOM,而easyExecl中可以设定阈值,防止溢出,所以选用了EasyExecl。
引入依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>2.2.6</version>
</dependency>
下载模板
这里模板为空,需要模板数据的话自行new对象,调用list.add().
@PostMapping("/exportTemplate")
@ApiOperation(value = "下载模板", notes = "下载模板")
public void exportTemplate(HttpServletResponse response) throws Exception {
try {
List<UserData> list = null;
response.setContentType("application/octet-stream;charset=utf-8");
response.setCharacterEncoding("utf-8");
// 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
String fileName = URLEncoder.encode("exportExcel", "UTF-8");
response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
EasyExcel.write(response.getOutputStream(), Person.class).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));
}
}
模板内容
@Data
public class UserData implements Serializable {
@ExcelProperty("姓名")
private String name;
@ExcelProperty("性别")
private String sex;
@ExcelProperty( "年龄")
private int age;
@ExcelProperty(“生日日期")
@DateTimeFormat("yyyy-MM-dd")
private LocalDate birth;
}