当前位置: 代码迷 >> 综合 >> EasyExcel 导出报表
  详细解决方案

EasyExcel 导出报表

热度:83   发布时间:2024-03-09 07:58:05.0

使用阿里的EasyExcel导出简单的报表

阿里easyExcel官网文档

1.导入依赖

<dependency><groupId>cglib</groupId><artifactId>cglib</artifactId><version>3.1</version>
</dependency>
<dependency><groupId>ch.qos.logback</groupId><artifactId>logback-classic</artifactId><version>1.2.3</version><scope>test</scope>
</dependency>
<dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.71</version><scope>test</scope>
</dependency>
<dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>1.18.8</version><scope>test</scope>
</dependency>
<dependency><groupId>com.alibaba</groupId><artifactId>easyexcel</artifactId><version>2.2.6</version>
</dependency>

2.新建实体,导出用

@Data
public class DemoData {
    @ExcelProperty({
    "测试","字符串标题"}, index = 0)private String string;@DateTimeFormat("yyyy年mm月dd日HH时mm分ss秒")@ExcelProperty({
    "测试","日期标题"}, index = 1)private Date date;@ExcelProperty({
    "测试","数字标题"}, index = 2)private Double doubleData;/*** 忽略这个字段*/@ExcelIgnoreprivate String ignore;//生成set get方法
}

3.利用jar包中封装的方法,弹框导出。。。想要什么颜色自己看文档,可以直接加

/*** 文件下载并且失败的时候返回json(默认失败了会返回一个有部分数据的Excel)** @since 2.1.1*/@GetMapping("downloadFailedUsingJson")public void downloadFailedUsingJson(HttpServletResponse response) throws IOException {
    // 这里注意 有同学反应使用swagger 会导致各种问题,请直接用浏览器或者用postmantry {
    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*=utf-8''" + fileName + ".xlsx");// 这里需要设置不关闭流EasyExcel.write(response.getOutputStream(), ExcelDto.class).autoCloseStream(Boolean.FALSE).includeColumnFiledNames(includeColumnFiledNames).sheet("模板").doWrite(listFileEntity);} catch (Exception e) {
    // 重置responseresponse.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));}}