EasyExcel使用筆記


簡介

EasyExcel重寫了poi對07版Excel的解析,能夠原本一個3M的excel用POI sax依然需要100M左右內存降低到幾M,並且再大的excel不會出現內存溢出,03版依賴POI的sax模式。在上層做了模型轉換的封裝,讓使用者更加簡單方便

GitHub地址https://github.com/alibaba/easyexcel

使用

注意: excel文件用的個人考勤表,放在項目根路徑

boot項目導入pom依賴

   <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>easyexcel</artifactId>
            <version>1.1.2-beta5</version>
        </dependency>

創建簡單的模型類

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


@Data
public class ExcelPropertyIndexModel extends BaseRowModel {

    @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 = 6)
    private String last;
    
}

創建監聽器(解析)

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

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


@Slf4j
@Component
public class ExcelListener extends AnalysisEventListener {

    public List<List<Object>> datas = new ArrayList<>();

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

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

    @Override
    public void invoke(Object object, AnalysisContext context) {
        List<Object> stringList = (List<Object>) object;
        datas.add(stringList);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        //解析結束銷毀不用的資源
        // datas.clear();
    }
}

創建工具類(讀取,導出)

@Slf4j
public class ExcelUtils {

    /**
     * 解析excel文件內容
     *
     * @param fileName
     * @return
     */
    public static List<List<Object>> readExcel(String fileName) {

        File file = new File(fileName);
        InputStream inputStream = null;
        try {
            inputStream = new FileInputStream(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        // 解析每行結果在listener中處理
        ExcelListener listener = new ExcelListener();
        ExcelReader excelReader = new ExcelReader(inputStream, ExcelTypeEnum.XLS, null, listener);
        excelReader.read();
        List<List<Object>> datas = listener.getDatas();
        return datas;
    }



    /**
     * 導出方法,生成excle
     *
     * @param filePath 絕對路徑,
     * @param data     數據源
     * @param sheet    excle頁面樣式
     */
    public static void writeSimpleBySheet(String filePath, List<List<Object>> data, Sheet sheet) {

        OutputStream outputStream = null;
        ExcelWriter writer = null;
        try {
            outputStream = new FileOutputStream(filePath);
            writer = EasyExcelFactory.getWriter(outputStream);
            writer.write1(data, sheet);
        } catch (FileNotFoundException e) {
            log.error("找不到文件或文件路徑錯誤, 文件:{}", filePath);
        } finally {
            try {
                if (writer != null) {
                    writer.finish();
                }
                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (IOException e) {
                log.error("excel文件導出失敗, 失敗原因:{}", e);
            }
        }
    }
    
} 

創建Controller類查看實現效果

@RestController
@RequestMapping("/excel")
@Slf4j
public class ExcelController {

    /**
     * 導入(解析)EXCEL文件
     * @return
     */
    @GetMapping("/writerExcel")
    @ResponseBody
    public List<List<Object>> writerExcel() {
        List<List<Object>> lists = ExcelUtils.readExcel("withHead.xls");
        if (lists != null) {
            log.info("表數據:"+lists);
        } else {
           log.info("空異常!");
        }
        return lists;
    }


    /**
     * 導出EXCEL文件
     * @param filePath 文件絕對路徑
     */
    @PostMapping(value = "/exportExcel")
    public void exportExcel(@ApiParam(name="filePath",value="文件路徑",required=true) @RequestParam String filePath){
        //木有數據庫數據源,用xls的解析數據當作數據源
        List<List<Object>> lists = ExcelUtils.readExcel("withHead.xls");
        Sheet sheet1 = new Sheet(1, 0, ExcelPropertyIndexModel.class);
        ExcelUtils.writeSimpleBySheet(filePath,lists,sheet1);
    }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM