Easyexcel使用-通用导出工具类

Easyexcel使用-简单导出

以前操作现在对excel操作需要POI的,现在有一个包已经封装好了,那么就是Easyexcel,他是阿里搞得工具。有利也有弊,酌情使用。

引入依赖

  <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>easyexcel</artifactId>
            <version>2.1.6</version>
        </dependency>


编写工具类


package com.tieta.web.util;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

public class ExcelUtil<T> {

    /**
     * @Author caicai
     * @Description EXCEL 操作类
     * @Date 8:18 2022/7/1
     * @Param  response 响应头
     * @Param  list 传入的数据
     * @Param  clazz excel 实体类
     * @return
     **/
    public  static<T> void writeExcel(HttpServletResponse response, List<T> list,Class clazz) throws IOException {
        //获取写输出流
        ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).build();
        //设置一个sheet对象: 第一个参数标识 第一个sheet ,第二个参数 工作簿名称。 设置表头
        WriteSheet sheet = EasyExcel.writerSheet(0,"sheet1").head(clazz).build();
        //开始写
        excelWriter.write(list,sheet);
        //完毕,会自动关闭输出流
        excelWriter.finish();
    }


}

控制层编写


    /**
     * @Author caicai
     * @Description 文件导出
     * @Date 9:17 2022/7/1
     * @Param  [response]
     * @return void
     **/
    @GetMapping("/export")
    public void export(HttpServletResponse response){

        try {
            //设置响应体
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            String fileName = "BaseStationInfo-"+DateUtil.now();
          //设置响应头
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

            // List<xxxx> list = "数据源";

           List<BaseStationManagementInfoExcel> excelList = list.stream().map(e->{
               BaseStationManagementInfoExcel excel = new BaseStationManagementInfoExcel();
               BeanUtils.copyProperties(e,excel);
               return excel;
           }).collect(Collectors.toList());

            //xxxx.class 就是表头 类 
            ExcelUtil.writeExcel(response,excelList,xxxx.class);


        }catch (IOException e){

            throw new RuntimeException("数据导出异常!");
        }

    }


表头类设置


@Data
@HeadRowHeight(value = 43) //表头高度
public class BaseStationManagementInfoExcel {
    /**
     * 主键ID
    */
//    @ExcelProperty(value = "id-标识ID",index = 0)
//    @ColumnWidth(10)
//    private BigInteger id;

    /**
     * 站址编码
     */
    @ExcelProperty(value = "addressCode-地址",index = 1)
    @ColumnWidth(20)

    private String  addressCode;
}


posted @ 2022-07-01 18:05  菜菜920  阅读(1062)  评论(0编辑  收藏  举报