EasyExcel通用工具类

  |   0 评论   |   0 浏览

EasyExcel通用工具类

hello大家好,我是llp。今天呢记录一下EasyExcel的基本使用,同时呢也分享给大家。

官方网站

https://github.com/alibaba/easyexcel

快速开始:https://www.yuque.com/easyexcel/doc/easyexcel

主备工作

1.1 新建maven工程引入相关依赖

image-20211219203056791

<dependencies>

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

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-simple</artifactId>
            <version>1.7.5</version>
        </dependency>

        <dependency>
            <groupId>org.apache.xmlbeans</groupId>
            <artifactId>xmlbeans</artifactId>
            <version>3.1.0</version>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.12</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>

    </dependencies>

1.2 定义一个要导出的对象

@Data
public class ExcelStudentDTO {

    @ExcelProperty("姓名")
    private String name;

    @ExcelProperty("生日")
    private Date birthday;

    @ExcelProperty("薪资")
    private Double salary;
    
    /**
     * 忽略这个字段
     */
    @ExcelIgnore
    private String ignore;
}

简单的写入Excel

public class ExcelWriteTest {
    /**
     * 写入xlsx
     */
    @Test
    public void simpleWriteXlsx() {
        String fileName = "C:/Users/asus/Desktop/simpleWrite.xlsx"; //需要提前新建目录
        // 这里 需要指定写用哪个class去写,然后写到第一个sheet,名字为模板 然后文件流会自动关闭
        // 如果这里想使用03 则 传入excelType参数即可
        EasyExcel.write(fileName, ExcelStudentDTO.class).excelType(ExcelTypeEnum.XLSX).sheet("模板").doWrite(data());
    }

    /**
     * 写入xls
     */
    @Test
    public void simpleWriteXls() {
        String fileName = "C:/Users/asus/Desktop/simpleWrite.xls"; //需要提前新建目录
        // 这里 需要指定写用哪个class去写,然后写到第一个sheet,名字为模板 然后文件流会自动关闭
        // 如果这里想使用03 则 传入excelType参数即可
        EasyExcel.write(fileName, ExcelStudentDTO.class).excelType(ExcelTypeEnum.XLS).sheet("模板").doWrite(data());
    }

    //辅助方法
    private List<ExcelStudentDTO> data() {
        List<ExcelStudentDTO> list = new ArrayList<ExcelStudentDTO>();
        //算上标题,做多可写65536行
        //超出:java.lang.IllegalArgumentException: Invalid row number (65536) outside allowable range (0..65535)
        for (int i = 0; i < 65535; i++) {
            ExcelStudentDTO data = new ExcelStudentDTO();
            data.setName("Helen" + i);
            data.setBirthday(new Date());
            data.setSalary(123456.1234);
            list.add(data);
        }
        return list;
    }
}

简单的读Excel

public class ExcelWriteTest {
    /**
     * 写入xlsx
     */
    @Test
    public void simpleWriteXlsx() {
        String fileName = "C:/Users/asus/Desktop/simpleWrite.xlsx"; //需要提前新建目录
        // 这里 需要指定写用哪个class去写,然后写到第一个sheet,名字为模板 然后文件流会自动关闭
        // 如果这里想使用03 则 传入excelType参数即可
        EasyExcel.write(fileName, ExcelStudentDTO.class).excelType(ExcelTypeEnum.XLSX).sheet("模板").doWrite(data());
    }

    /**
     * 写入xls
     */
    @Test
    public void simpleWriteXls() {
        String fileName = "C:/Users/asus/Desktop/simpleWrite.xls"; //需要提前新建目录
        // 这里 需要指定写用哪个class去写,然后写到第一个sheet,名字为模板 然后文件流会自动关闭
        // 如果这里想使用03 则 传入excelType参数即可
        EasyExcel.write(fileName, ExcelStudentDTO.class).excelType(ExcelTypeEnum.XLS).sheet("模板").doWrite(data());
    }

    //辅助方法
    private List<ExcelStudentDTO> data() {
        List<ExcelStudentDTO> list = new ArrayList<ExcelStudentDTO>();
        //算上标题,做多可写65536行
        //超出:java.lang.IllegalArgumentException: Invalid row number (65536) outside allowable range (0..65535)
        for (int i = 0; i < 65535; i++) {
            ExcelStudentDTO data = new ExcelStudentDTO();
            data.setName("Helen" + i);
            data.setBirthday(new Date());
            data.setSalary(123456.1234);
            list.add(data);
        }
        return list;
    }
}

EasyExcel工具类

监听器

/**
 * excel读取监听器
 *
 * @author xhl
 */
public class ExcleDataListener extends AnalysisEventListener {
	//定义一个保存Excel所有记录的集合
    private List<Object> list = new LinkedList<>();
    //回调接口
    private ExcleFinshCallBack callBack;

    /**
     * 构造注入ExcleFinshCallBack
     * @param callBack
     */
    public ExcleDataListener(ExcleFinshCallBack callBack) {
        this.callBack = callBack;
    }


    /**
     * 这个每一条数据解析都会来调用
     * 我们将每一条数据都保存到list集合中
     * @param data    one row value. Is is same as {@link AnalysisContext#readRowHolder()}
     * @param context
     */
    @Override
    public void invoke(Object data, AnalysisContext context) {
        list.add(data);
    }

    /**
     * 所有数据解析完成了 都会来调用
     * 解析完成之后将所有数据存入回调接口中
     * @param context
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        this.callBack.doAfterAllAnalysed(this.list);
    }
}

回调接口

/**
 * excel读取数据完成
 */
public interface ExcleFinshCallBack {
    void doAfterAllAnalysed(List<Object> result);
}

工具类

public class ExcleUtils {

    /**
     * excel读取
     *
     * @param file     excel文件
     * @param head     列名
     * @param callBack 回调 导入时传入定义好的回调接口,excel数据解析完毕之后监听器将数据传入回调函数
     * 这样我们调用工具类时可以通过回调函数获取导入的数据,如果数据量过大可根据实际情况进行分配入库
     */
    public static void importUserByExcel(MultipartFile file, Class head, ExcleFinshCallBack callBack) {
        try {
            EasyExcel.read(file.getInputStream(), head, new ExcleDataListener(callBack)).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 导出数据
     *
     * @param head      类名
     * @param excelname excel名字
     * @param data      数据
     */

    public static void getExcelimporttemplate(Class head, String excelname, List data) {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletResponse response = requestAttributes.getResponse();
        // 这里注意 有同学反应使用swagger 会导致各种问题,请直接用浏览器或者用postman
        //response.setContentType("application/vnd.ms-excel");
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        //response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
        response.setCharacterEncoding("utf-8");

        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        try {
            //表格头部样式
            WriteCellStyle headWriteCellStyle = new WriteCellStyle();
            //设置背景颜色
            //headWriteCellStyle.setFillForegroundColor(IndexedColors.WHITE.getIndex());
            //设置头字体
            //WriteFont headWriteFont = new WriteFont();
            //headWriteFont.setFontHeightInPoints((short)13);
            //headWriteFont.setBold(true);
            //headWriteCellStyle.setWriteFont(headWriteFont);
            //设置头居中
            headWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);

            //表格内容样式
            WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
            //设置 水平居中
            contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);

            HorizontalCellStyleStrategy horizontalCellStyleStrategy = new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);
            String fileName = URLEncoder.encode(excelname, "UTF-8").replaceAll("\\+", "+");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream(), head).registerWriteHandler(horizontalCellStyleStrategy).sheet("Sheet1").doWrite(data);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }




    /**
     * 导出数据
     *
     * @param head      类名
     * @param excelname excel名字
     * @param data      数据
     */
    public static void excelExport(Class head, String excelname, List data) {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletResponse response = requestAttributes.getResponse();
        // 这里注意 有同学反应使用swagger 会导致各种问题,请直接用浏览器或者用postman
        //response.setContentType("application/vnd.ms-excel");
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        try {
            String fileName = URLEncoder.encode(excelname, "UTF-8").replaceAll("\\+", "+");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream(), head).sheet("Sheet1").doWrite(data);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }





    /**
     * 导出数据二级表头
     *
     * @param head      类名
     * @param excelname excel名字
     * @param data      数据
     */

    public static void getBigTitleExcel(String bigTitle, Class head, String excelname, List data,List<String> header) {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletResponse response = requestAttributes.getResponse();
        // 这里注意 有同学反应使用swagger 会导致各种问题,请直接用浏览器或者用postman
        //response.setContentType("application/vnd.ms-excel");
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        //response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
        response.setCharacterEncoding("utf-8");

        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        try {
            //表格头部样式
            WriteCellStyle headWriteCellStyle = new WriteCellStyle();
            //设置背景颜色
            //headWriteCellStyle.setFillForegroundColor(IndexedColors.WHITE.getIndex());
            //设置头字体
            //WriteFont headWriteFont = new WriteFont();
            //headWriteFont.setFontHeightInPoints((short)13);
            //headWriteFont.setBold(true);
            //headWriteCellStyle.setWriteFont(headWriteFont);
            //设置头居中
            headWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);

            //表格内容样式
            WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
            //设置 水平居中
            contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);

            HorizontalCellStyleStrategy horizontalCellStyleStrategy = new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);
            String fileName = URLEncoder.encode(excelname, "UTF-8").replaceAll("\\+", "+");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream()).head(getExcelHeader(header, bigTitle)).registerWriteHandler(horizontalCellStyleStrategy).sheet("Sheet1").doWrite(data);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    private static List<List<String>> getExcelHeader(List<String> header, String bigTitle) {
        List<List<String>> head = new ArrayList<>();
        List<String> head0 = new ArrayList<>();
        for (String h : header) {
            head0 = new ArrayList<>();
            head0.add(bigTitle);
            head0.add(h);
            head.add(head0);
        }
        return head;
    }
}

工具类的使用

@PostMapping("/unit/inputExcel")
    @ResponseStatus(HttpStatus.CREATED)
    @PostLog("导入Excel操作")
    public void inputExcel(@RequestBody MultipartFile file) throws IOException {

        new ExcleUtils().importUserByExcel(file, OutputExcelVo.class, new ExcleFinshCallBack() {
            //重新回调接口的回调方法,通过回调函数获取导入excel的数据,如果数据量过大可以分批导入
            @Override
            public void doAfterAllAnalysed(List<Object> result) {
                unitManager.excelToInformation(result);
            }
        });
    }

标题:EasyExcel通用工具类
作者:llp
地址:https://blog.llp1110.cn/articles/2021/12/31/1640929038472.html