之前在使用easyExcel的时候发现网上对于easyExcel web下载介绍比较少,所以我想着出个比较简单的文章帮助大家了解 easyExcel的使用。
一、首先我们需要导入pom依赖:
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>2.2.10</version>
</dependency>
二、创建实体类 DemoData:
@Data
//设置背景色为空白,不使用easyExcel默认灰色背景 (有一说一默认背景是真的丑!)
@HeadStyle(fillPatternType = FillPatternType.NO_FILL, fillForegroundColor = 10)
public class DemoData {
@ExcelProperty("字符串标题") //excel表头
private String string;
@ExcelProperty("日期标题")
private Date date;
@ExcelProperty("数字标题")
private Double doubleData;
/**
* 忽略这个字段
*/
@ExcelIgnore
private String ignore;
}
注意:我这里是使用了Lombok插件 生成的 set、get 方法,如果没用这个插件,记得要手动写好set、和get、方法哦,因为easyExcel官方文档明确说明 实体类必须要有 get和set方法
三、编写导入工具类
//无填充方式导出并下载xlsx
public static void downloadUnfilledToXlsx(String excelName, HttpServletResponse response, Class cla, List list) throws IOException {
// 这里注意 使用swagger 会导致各种问题,easyexcel官方文档推荐直接用浏览器或者用postman测试
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.setCharacterEncoding("utf-8");
// 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
String fileName = URLEncoder.encode(excelName, "UTF-8").replaceAll("\\+", "%20");
response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
EasyExcel.write(response.getOutputStream(), cla).sheet(excelName).doWrite(list);
}
四、为实体类注入数据
这里就简简单单注入些 测试数据
private List<DemoData> data() {
List<DemoData> list = new ArrayList<DemoData>();
for (int i = 0; i < 10; i++) {
DemoData data = new DemoData();
data.setString("字符串" + i);
data.setDate(new Date());
data.setDoubleData(0.56+i);
list.add(data);
}
return list;
}
五、编写Controller接口
@RequestMapping("/download")
public void download(HttpServletResponse response) throws IOException {
EasyExcelUtils.downloadUnfilledToXlsx("easyExcel测试",response,DemoData.class,data());
}
六、浏览器测试功能
下载后:
打开后: