SpringBoot 2.2.5 整合EasyExcel 2.1.6,附帶Excel操作工具類,Excel文件轉CSV格式工具類

說明

  1. EasyExcel重寫了poi對07版Excel的解析,降低了內存消耗,對模型轉換進行了封裝,然后寫了下簡單案例。
  2. 完整代碼地址在結尾??!

第一步,導入maven依賴

<!-- 阿里開源框架EasyExcel -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>easyexcel</artifactId>
    <version>2.1.6</version>
</dependency>
<!-- 將excel轉成csv格式的poi依賴 -->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>4.1.0</version>
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>4.1.0</version>
</dependency>

第二步,創(chuàng)建模型解析監(jiān)聽器,以下提供兩種方式

第一種,創(chuàng)建模型解析監(jiān)聽器類,ModelExcelListener

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;

import java.util.ArrayList;
import java.util.List;
/**
 * @Description: 模型解析監(jiān)聽器 -- 每解析一行會回調invoke()方法,整個excel解析結束會執(zhí)行doAfterAllAnalysed()方法
 * @Author: jinhaoxun
 * @Date: 2020/1/14 15:51
 * @Version: 1.0.0
 */
public class ModelExcelListener<E> extends AnalysisEventListener<E> {

    private List<E> dataList = new ArrayList<E>();

    @Override
    public void invoke(E object, AnalysisContext context) {
        dataList.add(object);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
    }

    public List<E> getDataList() {
        return dataList;
    }

    public void setDataList(List<E> dataList) {
        this.dataList = dataList;
    }
}

第二種,創(chuàng)建StringList解析監(jiān)聽器類,StringExcelListener

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;

import java.util.ArrayList;
import java.util.List;

/**
 * @Description: StringList 解析監(jiān)聽器
 * @Author: jinhaoxun
 * @Date: 2020/1/15 11:31
 * @Version: 1.0.0
 */
public class StringExcelListener extends AnalysisEventListener {
    /**
     * 自定義用于暫時存儲data
     * 可以通過實例獲取該值
     */
    private List<List<String>> datas = new ArrayList<List<String>>();

    /**
     * 每解析一行都會回調invoke()方法
     *
     * @param object
     * @param context
     */
    @Override
    public void invoke(Object object, AnalysisContext context) {
        List<String> stringList= (List<String>) object;
        //數(shù)據(jù)存儲到list,供批量處理,或后續(xù)自己業(yè)務邏輯處理。
        datas.add(stringList);
        //根據(jù)自己業(yè)務做處理
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        //解析結束銷毀不用的資源
        //注意不要調用datas.clear(),否則getDatas為null
    }

    public List<List<String>> getDatas() {
        return datas;
    }

    public void setDatas(List<List<String>> datas) {
        this.datas = datas;
    }
}

第三步,分別創(chuàng)建三個模型類,ExcelModel,ExcelModel1,ExcelModel2

ExcelModel

import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.metadata.BaseRowModel;
import lombok.Data;

/**
 * @Description: 生成excel文件數(shù)據(jù)字段模板
 * @Author: jinhaoxun
 * @Date: 2020/1/14 15:45
 * @Version: 1.0.0
 */
@Data
public class ExcelModel extends BaseRowModel {

    public ExcelModel(){
    }

    public ExcelModel(String dateJuly, String onDuty, String offDuty, String overtime, String last){
        this.dateJuly = dateJuly;
        this.onDuty = onDuty;
        this.offDuty = offDuty;
        this.overtime = overtime;
        this.last = last;
    }

    @ExcelProperty(value = "日期", index = 0)
    private String dateJuly;
    @ExcelProperty(value = "上班時間", index = 1)
    private String onDuty;
    @ExcelProperty(value = "下班時間", index = 2)
    private String offDuty;
    @ExcelProperty(value = "加班時長", index = 3)
    private String overtime;
    @ExcelProperty(value = "備注", index = 4)
    private String last;

}

ExcelModel1

import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.metadata.BaseRowModel;
import lombok.Data;

/**
 * @Description: 生成excel文件數(shù)據(jù)字段模板
 * @Author: jinhaoxun
 * @Date: 2020/1/14 15:45
 * @Version: 1.0.0
 */
@Data
public class ExcelModel1 extends BaseRowModel {

    public ExcelModel1(){
    }

    public ExcelModel1(String dateJuly, String onDuty, String offDuty, String overtime, String last){
        this.dateJuly = dateJuly;
        this.onDuty = onDuty;
        this.offDuty = offDuty;
        this.overtime = overtime;
        this.last = last;
    }

    @ExcelProperty(value = "日期", index = 0)
    private String dateJuly;
    @ExcelProperty(value = "上班時間", index = 1)
    private String onDuty;
    @ExcelProperty(value = "下班時間", index = 2)
    private String offDuty;
    @ExcelProperty(value = "加班時長", index = 3)
    private String overtime;
    @ExcelProperty(value = "備注", index = 4)
    private String last;

}

ExcelModel2

import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.metadata.BaseRowModel;
import lombok.Data;

/**
 * @Description: 生成excel文件數(shù)據(jù)字段模板
 * @Author: jinhaoxun
 * @Date: 2020/1/14 15:45
 * @Version: 1.0.0
 */
@Data
public class ExcelModel2 extends BaseRowModel {

    public ExcelModel2(){
    }

    public ExcelModel2(String dateJuly, String onDuty, String offDuty, String overtime, String last){
        this.dateJuly = dateJuly;
        this.onDuty = onDuty;
        this.offDuty = offDuty;
        this.overtime = overtime;
        this.last = last;
    }

    @ExcelProperty(value = "日期", index = 0)
    private String dateJuly;
    @ExcelProperty(value = "上班時間", index = 1)
    private String onDuty;
    @ExcelProperty(value = "下班時間", index = 2)
    private String offDuty;
    @ExcelProperty(value = "加班時長", index = 3)
    private String overtime;
    @ExcelProperty(value = "備注", index = 4)
    private String last;

}

第四步,創(chuàng)建工具類,DataConvertUtil,ExcelUtil,ExcelConvertCsvUtil

DataConvertUtil

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * @Description:
 * @Author: jinhaoxun
 * @Date: 2020/4/14 下午5:26
 * @Version: 1.0.0
 */
public class DataConvertUtil {

    /**
     * @Author: jinhaoxun
     * @Description: 將inputStream轉byte[]
     * @param inputStream 輸入流
     * @Date: 2020/1/16 21:43
     * @Return: byte[]
     * @Throws: Exception
     */
    public static byte[] inputStreamTobyte2(InputStream inputStream) throws IOException {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        byte[] buff = new byte[100];
        int rc = 0;
        while ((rc = inputStream.read(buff, 0, 100)) > 0) {
            byteArrayOutputStream.write(buff, 0, rc);
        }
        return byteArrayOutputStream.toByteArray();
    }

    /**
     * @Author: jinhaoxun
     * @Description: 將byte[]轉inputStream
     * @param bytes byte數(shù)組
     * @Date: 2020/1/16 21:43
     * @Return: InputStream
     * @Throws: Exception
     */
    public static InputStream byte2ToInputStream(byte[] bytes) {
        return new ByteArrayInputStream(bytes);
    }

}

ExcelUtil

import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.BaseRowModel;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.metadata.Table;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.jinhaoxun.easyexcel.listener.ModelExcelListener;
import com.jinhaoxun.easyexcel.listener.StringExcelListener;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * @Description: excel導入導出工具類
 * 1.支持按行導入字符串方式
 * 2.支持導入實體類映射
 * 3.支持按行導出字符串方式
 * 4.支持導出實體類映射
 * @Author: jinhaoxun
 * @Date: 2020/1/15 11:20
 * @Version: 1.0.0
 */
public class ExcelUtil {

    /**
     * @Author: jinhaoxun
     * @Description: 使用 StringList 來讀取Excel
     * @param inputStream Excel的輸入流
     * @param excelTypeEnum Excel的格式(XLS或XLSX)
     * @Date: 2020/1/16 21:40
     * @Return: java.util.List<java.util.List<java.lang.String>>
     * @Throws: Exception
     */
    public static List<List<String>> readExcel(InputStream inputStream, ExcelTypeEnum excelTypeEnum) throws Exception{
        StringExcelListener listener = new StringExcelListener();
        ExcelReader excelReader = new ExcelReader(inputStream, excelTypeEnum, null, listener);
        excelReader.read();
        return listener.getDatas();
    }

    /**
     * @Author: jinhaoxun
     * @Description: 使用模型來讀取Excel
     * @param inputStream Excel的輸入流
     * @param clazz 模型的類
     * @param excelTypeEnum Excel的格式(XLS或XLSX)
     * @Date: 2020/1/16 21:41
     * @Return: java.util.List<E>
     * @Throws: Exception
     */
    public static <E> List<E> readExcel(InputStream inputStream, Class<? extends BaseRowModel> clazz, ExcelTypeEnum excelTypeEnum) throws Exception {
        // 解析每行結果在listener中處理
        ModelExcelListener<E> listener = new ModelExcelListener<E>();
        ExcelReader excelReader = new ExcelReader(inputStream, excelTypeEnum, null, listener);
        //默認只有一列表頭
        excelReader.read(new Sheet(1, 1, clazz));
        return listener.getDataList();
    }

    /**
     * @Author: jinhaoxun
     * @Description: 使用StringList來寫入Excel,單sheet,單table
     * @param outputStream Excel的輸出流
     * @param data 要寫入的以StringList為單位的數(shù)據(jù)
     * @param table 配置Excel的表的屬性
     * @param excelTypeEnum Excel的格式(XLS或XLSX)
     * @Date: 2020/1/16 21:42
     * @Return: void
     * @Throws: Exception
     */
    public static void writeExcel(OutputStream outputStream, List<List<String>> data, Table table, ExcelTypeEnum excelTypeEnum) throws Exception {
        /**
         * @Author: jinhaoxun
         * @Description:
         * @param outputStream
         * @param data
         * @param table
         * @param excelTypeEnum
         * @Date: 2020/1/16 21:42
         * @Return: void
         * @Throws:
         */
        //這里指定不需要表頭,因為String通常表頭已被包含在data里
        ExcelWriter writer = new ExcelWriter(outputStream, excelTypeEnum,false);
        //寫第一個sheet, sheet1  數(shù)據(jù)全是List<String> 無模型映射關系,無表頭
        Sheet sheet1 = new Sheet(0, 0);
        writer.write0(data, sheet1,table);
        writer.finish();
    }

    /**
     * @Author: jinhaoxun
     * @Description: 使用StringList來寫入Excel,單sheet,單table(返回byte數(shù)組)
     * @param outputStream Excel的輸出流
     * @param data 要寫入的以StringList為單位的數(shù)據(jù)
     * @param table 配置Excel的表的屬性
     * @param excelTypeEnum Excel的格式(XLS或XLSX)
     * @Date: 2020/1/16 21:43
     * @Return: byte[]
     * @Throws: Exception
     */
    public static byte[] writeExcel(ByteArrayOutputStream outputStream, List<List<String>> data, Table table, ExcelTypeEnum excelTypeEnum) throws Exception {
        //這里指定不需要表頭,因為String通常表頭已被包含在data里
        ExcelWriter writer = new ExcelWriter(outputStream, excelTypeEnum,false);
        //寫第一個sheet, sheet1  數(shù)據(jù)全是List<String> 無模型映射關系,無表頭
        Sheet sheet1 = new Sheet(0, 0);
        writer.write0(data, sheet1,table);
        writer.finish();
        return outputStream.toByteArray();
    }

    /**
     * @Author: jinhaoxun
     * @Description: 使用模型來寫入Excel,單sheet,單table
     * @param outputStream Excel的輸出流
     * @param data 要寫入的以 模型 為單位的數(shù)據(jù)
     * @param clazz 模型的類
     * @param excelTypeEnum Excel的格式(XLS或XLSX)
     * @Date: 2020/1/16 21:43
     * @Return: byte[]
     * @Throws: Exception
     */
    public static void writeExcel(OutputStream outputStream, List<? extends BaseRowModel> data,
                                  Class<? extends BaseRowModel> clazz, ExcelTypeEnum excelTypeEnum) throws Exception {
        //這里指定需要表頭,因為model通常包含表頭信息
        ExcelWriter writer = new ExcelWriter(outputStream, excelTypeEnum,true);
        //寫第一個sheet, sheet1  數(shù)據(jù)全是List<String> 無模型映射關系
        Sheet sheet1 = new Sheet(1, 0, clazz);
        writer.write(data, sheet1);
        writer.finish();
    }

    /**
     * @Author: jinhaoxun
     * @Description: 使用模型來寫入Excel,單sheet,單table(返回字節(jié)數(shù)組)
     * @param outputStream Excel的輸出流
     * @param data 要寫入的以 模型 為單位的數(shù)據(jù)
     * @param clazz 模型的類
     * @param excelTypeEnum Excel的格式(XLS或XLSX)
     * @Date: 2020/1/16 21:43
     * @Return: byte[]
     * @Throws: Exception
     */
    public static byte[] writeExcel(ByteArrayOutputStream outputStream, List<? extends BaseRowModel> data,
                                    Class<? extends BaseRowModel> clazz, ExcelTypeEnum excelTypeEnum) throws Exception {
        //這里指定需要表頭,因為model通常包含表頭信息
        ExcelWriter writer = new ExcelWriter(outputStream, excelTypeEnum,true);
        //寫第一個sheet, sheet1  數(shù)據(jù)全是List<String> 無模型映射關系
        Sheet sheet1 = new Sheet(1, 0, clazz);
        writer.write(data, sheet1);
        writer.finish();
        return outputStream.toByteArray();
    }

    /**
     * @Author: jinhaoxun
     * @Description: 使用模型來寫入Excel,多sheet,單table (返回字節(jié)數(shù)組)
     * @param outputStream Excel的輸出流
     * @param sheetName  sheet名集合
     * @param datas  要寫入的以 模型 為單位的數(shù)據(jù)
     * @param clazzs  模型的類
     * @param excelTypeEnum  Excel的格式(XLS或XLSX)
     * @Date: 2020/1/16 21:43
     * @Return: byte[]
     * @Throws: Exception
     */
    public static byte[] writeExcel(ByteArrayOutputStream outputStream,List<String> sheetName,List<List<? extends BaseRowModel>> datas,
                                    List<Class<? extends BaseRowModel>> clazzs, ExcelTypeEnum excelTypeEnum) throws Exception {
        //這里指定需要表頭,因為model通常包含表頭信息
        ExcelWriter writer = new ExcelWriter(outputStream, excelTypeEnum,true);
        if (sheetName.size()!=datas.size()||datas.size()!=clazzs.size()){
            throw new ArrayIndexOutOfBoundsException();
        }
        int i = 0;
        //寫第一個sheet, sheet1  數(shù)據(jù)全是List<String> 無模型映射關系
        for (String name:sheetName){
            Sheet sheet1 = new Sheet(1, 0, clazzs.get(i));
            sheet1.setSheetName(name);
            writer.write(datas.get(i), sheet1);
        }
        writer.finish();
        return outputStream.toByteArray();
    }

    /**
     * @Author: jinhaoxun
     * @Description: 使用模型來寫入Excel,多sheet,多table
     * @param outputStream  Excel的輸出流
     * @param sheetAndTable sheet和table名,格式:<sheet名,<table名集合>>
     * @param data   <sheet名,<table名,table數(shù)據(jù)集>>
     * @param clazz  <sheet名,<table名,table數(shù)據(jù)集實體class類型>>
     * @param excelTypeEnum Excel的格式(XLS或XLSX)
     * @Date: 2020/1/16 21:43
     * @Return: byte[]
     * @Throws: Exception
     */
    public static byte[] writeExcel(ByteArrayOutputStream outputStream,Map<String,List<String>> sheetAndTable,
                                    Map<String,Map<String,List<? extends BaseRowModel>>> data,Map<String,Map<String,Class<? extends BaseRowModel>>> clazz,
                                    ExcelTypeEnum excelTypeEnum) throws Exception {

        //這里指定需要表頭,因為model通常包含表頭信息
        ExcelWriter writer = new ExcelWriter(outputStream, excelTypeEnum,true);

        Iterator<Map.Entry<String, List<String>>> iterator = sheetAndTable.entrySet().iterator();
        int sheetNo = 1;
        //遍歷sheet
        while (iterator.hasNext()){
            Map.Entry<String, List<String>> next = iterator.next();
            //當前sheet名
            String sheetName = next.getKey();
            //當前sheet對應的table的實體類class對象集合
            Map<String, Class<? extends BaseRowModel>> tableClasses = clazz.get(sheetName);
            //當前sheet對應的table的數(shù)據(jù)集合
            Map<String, List<? extends BaseRowModel>> dataListMaps = data.get(sheetName);
            Sheet sheet = new Sheet(sheetNo, 0);
            sheet.setSheetName(sheetName);
            int tableNo = 1;
            Iterator<Map.Entry<String, Class<? extends BaseRowModel>>> iterator1 = tableClasses.entrySet().iterator();
            //遍歷table
            while (iterator1.hasNext()){
                Map.Entry<String, Class<? extends BaseRowModel>> next1 = iterator1.next();
                //當前table名
                String tableName = next1.getKey();
                //當前table對應的class
                Class<? extends BaseRowModel> tableClass = next1.getValue();
                //當前table對應的數(shù)據(jù)集
                List<? extends BaseRowModel> tableData = dataListMaps.get(tableName);
                Table table = new Table(tableNo);
                table.setClazz(tableClass);
                writer.write(tableData, sheet, table);
                tableNo++;
            }
            sheetNo++;
        }
        writer.finish();
        return outputStream.toByteArray();
    }
}

ExcelConvertCsvUtil

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Description: excel文件轉成csv格式
 * @Author: jinhaoxun
 * @Date: 2020/4/14 上午10:07
 * @Version: 1.0.0
 */
public class ExcelConvertCsvUtil {

    /**
     * @Author: jinhaoxun
     * @Description: 將excel字節(jié)碼數(shù)組轉成csv字節(jié)碼數(shù)組
     * @param bytes excel字節(jié)碼數(shù)組
     * @Date: 2020/1/16 21:43
     * @Return: byte[]
     * @Throws: Exception
     */
    public static byte[] convertExcelToCsv(byte[] bytes) throws Exception {
        InputStream inputStream = new ByteArrayInputStream(bytes);
        Workbook wb = WorkbookFactory.create(inputStream);

        String buffer = "";
        Sheet sheet = null;
        Row row = null;
        List<Map<String,String>> list = null;
        String cellData = null;

        if(wb != null){
            //用來存放表中數(shù)據(jù)
            list = new ArrayList<Map<String,String>>();
            //獲取第一個sheet
            sheet = wb.getSheetAt(0);
            //獲取最大行數(shù)
            int rownum = sheet.getPhysicalNumberOfRows();
            //獲取第一行
            row = sheet.getRow(0);
            //獲取最大列數(shù)
            int colnum = row.getPhysicalNumberOfCells();
            for (int i = 0; i<rownum; i++) {
                row = sheet.getRow(i);
                for (int j = 0; j < colnum; j++) {
                    cellData = (String) getCellFormatValue(row.getCell(j));
                    buffer +=cellData;
                }
                buffer = buffer.substring(0, buffer.lastIndexOf(",")).toString();
                buffer += "\n";
            }

            return buffer.getBytes();
        }
        return null;
    }

    /**
     * @Author: jinhaoxun
     * @Description: 讀取excel
     * @param filePath 本地文件路徑
     * @Date: 2020/1/16 21:43
     * @Return: Workbook
     * @Throws: Exception
     */
    public static Workbook readExcel(String filePath){
        Workbook wb = null;
        if(filePath==null){
            return null;
        }
        String extString = filePath.substring(filePath.lastIndexOf("."));
        InputStream is = null;
        try {
            is = new FileInputStream(filePath);
            if(".xls".equals(extString)){
                return wb = new HSSFWorkbook(is);
            }else if(".xlsx".equals(extString)){
                return wb = new XSSFWorkbook(is);
            }else{
                return wb = null;
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return wb;
    }

    /**
     * @Author: jinhaoxun
     * @Description:
     * @param cell
     * @Date: 2020/1/16 21:43
     * @Return: Workbook
     * @Throws: Exception
     */
    public static Object getCellFormatValue(Cell cell){
        Object cellValue = null;
        if(cell!=null){
            //判斷cell類型
            switch(cell.getCellType()){
                case NUMERIC:{
                    cellValue = String.valueOf(cell.getNumericCellValue()).replaceAll("\n", " ") + ",";
                    break;
                }
                case FORMULA:{
                    //判斷cell是否為日期格式
                    if(DateUtil.isCellDateFormatted(cell)){
                        //轉換為日期格式YYYY-mm-dd
                        cellValue = String.valueOf(cell.getDateCellValue()).replaceAll("\n", " ") + ",";;
                    }else{
                        //數(shù)字
                        cellValue = String.valueOf(cell.getNumericCellValue()).replaceAll("\n", " ") + ",";;
                    }
                    break;
                }
                case STRING:{
                    cellValue = cell.getRichStringCellValue().getString().replaceAll("\n", " ") + ",";;
                    break;
                }
                default:
                    cellValue = "";
            }
        }else{
            cellValue = "";
        }
        return cellValue;
    }
}

第五步,編寫單元測試類,EasyexcelApplicationTests,并進行測試,使用方法基本都有注釋

import com.alibaba.excel.metadata.BaseRowModel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.jinhaoxun.easyexcel.entity.ExcelModel;
import com.jinhaoxun.easyexcel.entity.ExcelModel1;
import com.jinhaoxun.easyexcel.entity.ExcelModel2;
import com.jinhaoxun.easyexcel.util.DataConvertUtil;
import com.jinhaoxun.easyexcel.util.ExcelConvertCsvUtil;
import com.jinhaoxun.easyexcel.util.ExcelUtil;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
// 獲取啟動類,加載配置,確定裝載 Spring 程序的裝載方法,它回去尋找 主配置啟動類(被 @SpringBootApplication 注解的)
@SpringBootTest
class EasyexcelApplicationTests {

    @Test
    void readExcelTest() throws Exception {
        //讀取excel
        File file = new File("E:\\2.xlsx");
        InputStream inputStream = new FileInputStream(file);
        //導入excle
        List<ExcelModel> datas = ExcelUtil.readExcel(inputStream, ExcelModel.class, ExcelTypeEnum.XLSX);
        log.info(datas.toString());
    }

    @Test
    void writeExcelTest() throws Exception {
        //單sheet,單table導出測試
        List<ExcelModel> excelModelList = new ArrayList<ExcelModel>();
        for (int i = 0;i<5;i++){
            ExcelModel excelModel = new ExcelModel("日期"+i, "上班時間" + i,
                    "下班時間" + i, "加班時長" + i, "備注" + i);
            excelModelList.add(excelModel);
        }
        File file1 = new File("E:\\2.xlsx");
        ByteArrayOutputStream outputStream1 = new ByteArrayOutputStream();
        byte[] bytes = ExcelUtil.writeExcel(outputStream1, excelModelList, ExcelModel.class, ExcelTypeEnum.XLSX);
        FileOutputStream outputStream = new FileOutputStream(file1);
        outputStream.write(bytes);
    }

    @Test
    void writeExcelTest1() throws Exception {
        //多sheet,多table導出測試,數(shù)據(jù)集制作
        List<ExcelModel> excelModelList = new ArrayList<ExcelModel>();
        List<ExcelModel1> excelModel1List = new ArrayList<ExcelModel1>();
        List<ExcelModel2> excelModel2List = new ArrayList<ExcelModel2>();
        for (int i = 0;i<5;i++){
            ExcelModel excelModel = new ExcelModel("日期"+i, "上班時間" + i,
                    "下班時間" + i, "加班時長" + i, "備注" + i);
            ExcelModel1 excelModel1 = new ExcelModel1("日期"+i, "上班時間" + i,
                    "下班時間" + i, "加班時長" + i, "備注" + i);
            ExcelModel2 excelModel2 = new ExcelModel2("日期"+i, "上班時間" + i,
                    "下班時間" + i, "加班時長" + i, "備注" + i);

            excelModelList.add(excelModel);
            excelModel1List.add(excelModel1);
            excelModel2List.add(excelModel2);
        }
        Map<String,List<String>> sheetAndTable = new HashMap<String, List<String>>();
        //構造第一個sheet,此sheet內有兩個table
        List<String> sheet1tableNames = new ArrayList();
        sheet1tableNames.add("表一");
        sheet1tableNames.add("表二");
        //構造第二個sheet,此sheet內有一個table
        List<String> Sheet2tableNames = new ArrayList<String>();
        Sheet2tableNames.add("表三");
        sheetAndTable.put("sheet1",sheet1tableNames);
        sheetAndTable.put("sheet2",Sheet2tableNames);

        Map<String,Map<String,Class<? extends BaseRowModel>>> clazz = new HashMap<String, Map<String, Class<? extends BaseRowModel>>>();
        //第一個sheet
        Map<String,Class<? extends BaseRowModel>> tables = new HashMap<String, Class<? extends BaseRowModel>>();
        tables.put("表一",ExcelModel.class);
        tables.put("表二",ExcelModel1.class);
        clazz.put("sheet1",tables);
        Map<String,Class<? extends BaseRowModel>> tables1 = new HashMap<String, Class<? extends BaseRowModel>>();
        tables1.put("表三",ExcelModel2.class);
        clazz.put("sheet2",tables1);

        Map<String,Map<String,List<? extends BaseRowModel>>> data= new HashMap<String, Map<String, List<? extends BaseRowModel>>>();
        //第一個sheet
        Map<String,List<? extends BaseRowModel>> map1 = new HashMap<String, List<? extends BaseRowModel>>();
        map1.put("表一",excelModelList);
        map1.put("表二",excelModel1List);
        data.put("sheet1",map1);
        Map<String,List<? extends BaseRowModel>> map2 = new HashMap<String, List<? extends BaseRowModel>>();
        map2.put("表三",excelModel2List);
        data.put("sheet2",map2);

        File file1 = new File("E:\\3.xlsx");
        ByteArrayOutputStream outputStream1 = new ByteArrayOutputStream();
        byte[] bytes = ExcelUtil.writeExcel(outputStream1,sheetAndTable,data,clazz,ExcelTypeEnum.XLSX);
        FileOutputStream outputStream = new FileOutputStream(file1);
        outputStream.write(bytes);
    }

    @Test
    void convertExcelToCsvTest() throws Exception {
        //讀取excel
        File file = new File("/Users/ao/Desktop/activitycode_20200414102350.xlsx");
        InputStream inputStream = new FileInputStream(file);
        byte[] bytes = DataConvertUtil.inputStreamTobyte2(inputStream);
        ExcelConvertCsvUtil.convertExcelToCsv(bytes);
    }

    @BeforeEach
    void testBefore(){
        log.info("測試開始!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
    }

    @AfterEach
    void testAfter(){
        log.info("測試結束!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
    }

}

完整代碼地址:https://github.com/Jinhx128/springboot-demo

注:此工程包含多個module,本文所用代碼均在easyexcel-demo模塊下

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

友情鏈接更多精彩內容