相关文章链接
文件导出
获取 resources 目录下的文件,使用 withTemplate 获取文件流导出文件模板
@GetMapping("/download1")
public void download1(HttpServletResponse response) {
try (InputStream in = new ClassPathResource("测试.xls").getInputStream()) {
response.setContentType("application/vnd.ms-excel");
response.setCharacterEncoding("utf-8");
// 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
String fileName = URLEncoder.encode("测试", "UTF-8").replaceAll("\\+", "%20");
response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xls");
EasyExcel.write(response.getOutputStream())
.withTemplate(in)
.sheet("sheet1")
.doWrite(Collections.emptyList());
} catch (Exception e) {
e.printStackTrace();
}
}
注意:获取 resources 目录下的文件需要在 maven 中添加以下配置,过滤对应的文件,防止编译生成后的 class 文件找不到对应的文件信息
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<configuration>
<encoding>UTF-8</encoding>
<nonFilteredFileExtensions>
<nonFilteredFileExtension>xls</nonFilteredFileExtension>
<nonFilteredFileExtension>xlsx</nonFilteredFileExtension>
</nonFilteredFileExtensions>
</configuration>
</plugin>
对象填充导出
模板文件信息
@AllArgsConstructor
@NoArgsConstructor
@Data
public class User {
@ExcelProperty(value = "用户Id")
private Integer userId;
@ExcelProperty(value = "姓名")
private String name;
@ExcelProperty(value = "手机")
private String phone;
@ExcelProperty(value = "邮箱")
private String email;
@ExcelProperty(value = "创建时间")
private Date createTime;
}
@GetMapping("/download5")
public void download5(HttpServletResponse response) {
try (InputStream in = new ClassPathResource("测试3.xls").getInputStream()) {
response.setContentType("application/vnd.ms-excel");
response.setCharacterEncoding("utf-8");
// 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
String fileName = URLEncoder.encode("测试3", "UTF-8").replaceAll("\\+", "%20");
response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xls");
User user = new User(1, "张三", "12345678901", "zhangsan@qq.com", new Date());
EasyExcel.write(response.getOutputStream(), User.class)
.withTemplate(in)
.sheet("模板")
.doFill(user);
} catch (Exception e) {
e.printStackTrace();
}
}
注意:填充模板跟写文件使用的方法不一致,模板填充使用的方法是 doFill,而不是 doWrite
导出文件内容
List 填充导出
对象导出
模板文件信息