EasyExcel调试记录

一.pom.xml

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


二.必须要finish才会写入,不finish只会创建empty的文件。

WriteSheet writeSheet = EasyExcel.writerSheet("测试1").head(list).build();
        excelWriter.write(data, writeSheet);
        //必须要finish才会写入,不finish只会创建一个empty的文件。
        excelWriter.finish();


三.template和file不能是通一个,file会将template文件清掉。

//以下写法是错误的
ExcelWriter excelWriter2 = EasyExcel.write().withTemplate(filePath1st).file(filePath1st).autoCloseStream(true).build();


四.一个ExcelWriter能够写多个Sheet。

        //第一次写入
        ExcelWriter excelWriter = EasyExcel.write().file(filePath1st).autoCloseStream(true).build();
        WriteSheet writeSheet = EasyExcel.writerSheet("测试1").head(list).build();
        excelWriter.write(data, writeSheet);
        //第二次写入
        WriteSheet writeSheet2 = EasyExcel.writerSheet("测试2").head(list).build();
        excelWriter.write(data, writeSheet2);
       //必须要finish才会写入,不finish只会创建一个empty的文件。
        excelWriter.finish();


五.不支持多线程写

        //初始化 ExcelWriter
        ExcelWriter excelWriter = EasyExcel.write().file(filePath1st).build();
        
        for(int j=0;j<=9;j++)
        {
            WriteSheet writeSheet =  EasyExcel.writerSheet(j,"测试"+j).head(list).build();
            new Thread(new WriteSheetThread(excelWriter,writeSheet,data)).start();
        }

        excelWriter.finish();

如上写法是错误的,无法正确运行。

线程类代码如下

static class WriteSheetThread implements Runnable{
        private ExcelWriter excelWriter;
        private WriteSheet writeSheet;
        private List<List<Object>> data;

        public WriteSheetThread(ExcelWriter excelWriter, WriteSheet writeSheet, List<List<Object>> data) {
            this.excelWriter = excelWriter;
            this.writeSheet = writeSheet;
            this.data = data;
        }
        @Override
        public void run() {
            writeExcel();
        }
        private void writeExcel(){
            System.out.println(writeSheet);
            excelWriter.write(data, writeSheet);
        }
    }


六.正确写多个sheet的方式

        //初始化 ExcelWriter
        ExcelWriter excelWriter = EasyExcel.write().file(filePath1st).build();
        //正确流程,在单线程中依次写多个文件。
        for(int j=0;j<=9;j++)
        {
            WriteSheet writeSheet =  EasyExcel.writerSheet(j,"测试"+j).head(list).build();
            excelWriter.write(data, writeSheet);
        }
        excelWriter.finish();
posted @ 2020-07-08 11:34  Arli  阅读(1361)  评论(0编辑  收藏  举报