easyExcel使用

1.封裝工具類

@Slf4j
public class DefaultExcelListener<T> extends AnalysisEventListener<T> {
    private final List<T> rows = new ArrayList();

    @Override
    public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
        log.info("解析到一條頭數(shù)據(jù):{}", JSON.toJSONString(headMap));
    }

    @Override
    public void invoke(T object, AnalysisContext context) {
        rows.add(object);
        // 實(shí)際數(shù)據(jù)量比較大時(shí),rows里的數(shù)據(jù)可以存到一定量之后進(jìn)行批量處理(比如存到數(shù)據(jù)庫(kù))泳秀,
        // 然后清空列表秘血,以防止內(nèi)存占用過(guò)多造成OOM
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        log.info("read {} rows", rows.size());
    }

    /**
     * 在轉(zhuǎn)換異常 獲取其他異常下會(huì)調(diào)用本接口尽纽。拋出異常則停止讀取。如果這里不拋出異常則 繼續(xù)讀取下一行明也。
     *
     * @param exception
     * @param context
     * @throws Exception
     */
    @Override
    public void onException(Exception exception, AnalysisContext context) {
        log.error("解析失敗女嘲,但是繼續(xù)解析下一行:{}", exception.getMessage());
        if (exception instanceof ExcelDataConvertException) {
            ExcelDataConvertException excelDataConvertException = (ExcelDataConvertException) exception;
            log.error("第{}行,第{}列解析異常顿仇,數(shù)據(jù)為:{}", excelDataConvertException.getRowIndex(),
                    excelDataConvertException.getColumnIndex(), excelDataConvertException.getCellData());
        }
    }

    public List<T> getRows() {
        return rows;
    }
}
public class EasyExcelUtil {
    /**
     * 同步無(wú)模型讀(默認(rèn)讀取sheet0,從第2行開(kāi)始讀)
     *
     * @param filePath
     * @return
     */
    public static List<Map<Integer, String>> syncRead(String filePath) {
        return EasyExcelFactory.read(filePath).sheet().doReadSync();
    }

    /**
     * 同步無(wú)模型讀(默認(rèn)表頭占一行,從第2行開(kāi)始讀)
     *
     * @param filePath
     * @param sheetNo  sheet頁(yè)號(hào),從0開(kāi)始
     * @return
     */
    public static List<Map<Integer, String>> syncRead(String filePath, Integer sheetNo) {
        return EasyExcelFactory.read(filePath).sheet(sheetNo).doReadSync();
    }

    /**
     * 同步無(wú)模型讀(指定sheet和表頭占的行數(shù))
     *
     * @param inputStream
     * @param sheetNo     sheet頁(yè)號(hào)臼闻,從0開(kāi)始
     * @param headRowNum  表頭占的行數(shù)鸿吆,從0開(kāi)始(如果要連表頭一起讀出來(lái)則傳0)
     * @return List<Map < colNum, cellValue>>
     */
    public static List<Map<Integer, String>> syncRead(InputStream inputStream, Integer sheetNo, Integer headRowNum) {
        return EasyExcelFactory.read(inputStream).sheet(sheetNo).headRowNumber(headRowNum).doReadSync();
    }

    /**
     * 同步無(wú)模型讀(指定sheet和表頭占的行數(shù))
     *
     * @param file
     * @param sheetNo    sheet頁(yè)號(hào),從0開(kāi)始
     * @param headRowNum 表頭占的行數(shù)述呐,從0開(kāi)始(如果要連表頭一起讀出來(lái)則傳0)
     * @return List<Map < colNum, cellValue>>
     */
    public static List<Map<Integer, String>> syncRead(File file, Integer sheetNo, Integer headRowNum) {
        return EasyExcelFactory.read(file).sheet(sheetNo).headRowNumber(headRowNum).doReadSync();
    }

    /**
     * 同步無(wú)模型讀(指定sheet和表頭占的行數(shù))
     *
     * @param filePath
     * @param sheetNo    sheet頁(yè)號(hào)惩淳,從0開(kāi)始
     * @param headRowNum 表頭占的行數(shù),從0開(kāi)始(如果要連表頭一起讀出來(lái)則傳0)
     * @return List<Map < colNum, cellValue>>
     */
    public static List<Map<Integer, String>> syncRead(String filePath, Integer sheetNo, Integer headRowNum) {
        return EasyExcelFactory.read(filePath).sheet(sheetNo).headRowNumber(headRowNum).doReadSync();
    }

    /**
     * 同步按模型讀(默認(rèn)讀取sheet0,從第2行開(kāi)始讀)
     *
     * @param filePath
     * @param clazz    模型的類類型(excel數(shù)據(jù)會(huì)按該類型轉(zhuǎn)換成對(duì)象)
     * @return
     */
    public static <T> List<T> syncReadModel(String filePath, Class<T> clazz) {
        return EasyExcelFactory.read(filePath).sheet().head(clazz).doReadSync();
    }

    /**
     * 同步按模型讀(默認(rèn)表頭占一行市埋,從第2行開(kāi)始讀)
     *
     * @param filePath
     * @param clazz    模型的類類型(excel數(shù)據(jù)會(huì)按該類型轉(zhuǎn)換成對(duì)象)
     * @param sheetNo  sheet頁(yè)號(hào)黎泣,從0開(kāi)始
     * @return
     */
    public static List<T> syncReadModel(String filePath, Class<T> clazz, Integer sheetNo) {
        return EasyExcelFactory.read(filePath).sheet(sheetNo).head(clazz).doReadSync();
    }

    /**
     * 同步按模型讀(指定sheet和表頭占的行數(shù))
     *
     * @param inputStream
     * @param clazz       模型的類類型(excel數(shù)據(jù)會(huì)按該類型轉(zhuǎn)換成對(duì)象)
     * @param sheetNo     sheet頁(yè)號(hào),從0開(kāi)始
     * @param headRowNum  表頭占的行數(shù)缤谎,從1開(kāi)始(不帶表頭)
     * @return
     */
    public static <T> List<T> syncReadModel(InputStream inputStream, Class<T> clazz) {
        return syncReadModel(inputStream,clazz,0,1);
    }

    /**
     * 同步按模型讀(指定sheet和表頭占的行數(shù))
     *
     * @param inputStream
     * @param clazz       模型的類類型(excel數(shù)據(jù)會(huì)按該類型轉(zhuǎn)換成對(duì)象)
     * @param sheetNo     sheet頁(yè)號(hào)抒倚,從0開(kāi)始
     * @param headRowNum  表頭占的行數(shù),從0開(kāi)始(如果要連表頭一起讀出來(lái)則傳0)
     * @return
     */
    public static <T> List<T> syncReadModel(InputStream inputStream, Class<T> clazz, Integer sheetNo, Integer headRowNum) {
        return EasyExcelFactory.read(inputStream).sheet(sheetNo).headRowNumber(headRowNum).head(clazz).doReadSync();
    }

    /**
     * 同步按模型讀(指定sheet和表頭占的行數(shù))
     *
     * @param file
     * @param clazz      模型的類類型(excel數(shù)據(jù)會(huì)按該類型轉(zhuǎn)換成對(duì)象)
     * @param sheetNo    sheet頁(yè)號(hào)坷澡,從0開(kāi)始
     * @param headRowNum 表頭占的行數(shù)托呕,從0開(kāi)始(如果要連表頭一起讀出來(lái)則傳0)
     * @return
     */
    public static <T> List<T> syncReadModel(File file, Class<T> clazz, Integer sheetNo, Integer headRowNum) {
        return EasyExcelFactory.read(file).sheet(sheetNo).headRowNumber(headRowNum).head(clazz).doReadSync();
    }

    /**
     * 同步按模型讀(指定sheet和表頭占的行數(shù))
     *
     * @param filePath
     * @param clazz      模型的類類型(excel數(shù)據(jù)會(huì)按該類型轉(zhuǎn)換成對(duì)象)
     * @param sheetNo    sheet頁(yè)號(hào),從0開(kāi)始
     * @param headRowNum 表頭占的行數(shù)频敛,從0開(kāi)始(如果要連表頭一起讀出來(lái)則傳0)
     * @return
     */
    public static <T> List<T> syncReadModel(String filePath, Class<T> clazz, Integer sheetNo, Integer headRowNum) {
        return EasyExcelFactory.read(filePath).sheet(sheetNo).headRowNumber(headRowNum).head(clazz).doReadSync();
    }

    /**
     * 異步無(wú)模型讀(默認(rèn)讀取sheet0,從第2行開(kāi)始讀)
     *
     * @param excelListener 監(jiān)聽(tīng)器项郊,在監(jiān)聽(tīng)器中可以處理行數(shù)據(jù)LinkedHashMap,表頭數(shù)據(jù)斟赚,異常處理等
     * @param filePath      表頭占的行數(shù)着降,從0開(kāi)始(如果要連表頭一起讀出來(lái)則傳0)
     * @return
     */
    public static void asyncRead(String filePath, AnalysisEventListener<T> excelListener) {
        EasyExcelFactory.read(filePath, excelListener).sheet().doRead();
    }

    /**
     * 異步無(wú)模型讀(默認(rèn)表頭占一行,從第2行開(kāi)始讀)
     *
     * @param filePath      表頭占的行數(shù)拗军,從0開(kāi)始(如果要連表頭一起讀出來(lái)則傳0)
     * @param excelListener 監(jiān)聽(tīng)器任洞,在監(jiān)聽(tīng)器中可以處理行數(shù)據(jù)LinkedHashMap,表頭數(shù)據(jù)发侵,異常處理等
     * @param sheetNo       sheet頁(yè)號(hào)交掏,從0開(kāi)始
     * @return
     */
    public static void asyncRead(String filePath, AnalysisEventListener<T> excelListener, Integer sheetNo) {
        EasyExcelFactory.read(filePath, excelListener).sheet(sheetNo).doRead();
    }

    /**
     * 異步無(wú)模型讀(指定sheet和表頭占的行數(shù))
     *
     * @param inputStream
     * @param excelListener 監(jiān)聽(tīng)器,在監(jiān)聽(tīng)器中可以處理行數(shù)據(jù)LinkedHashMap刃鳄,表頭數(shù)據(jù)盅弛,異常處理等
     * @param sheetNo       sheet頁(yè)號(hào),從0開(kāi)始
     * @param headRowNum    表頭占的行數(shù)叔锐,從0開(kāi)始(如果要連表頭一起讀出來(lái)則傳0)
     * @return
     */
    public static void asyncRead(InputStream inputStream, AnalysisEventListener<T> excelListener, Integer sheetNo, Integer headRowNum) {
        EasyExcelFactory.read(inputStream, excelListener).sheet(sheetNo).headRowNumber(headRowNum).doRead();
    }

    /**
     * 異步無(wú)模型讀(指定sheet和表頭占的行數(shù))
     *
     * @param file
     * @param excelListener 監(jiān)聽(tīng)器挪鹏,在監(jiān)聽(tīng)器中可以處理行數(shù)據(jù)LinkedHashMap,表頭數(shù)據(jù)愉烙,異常處理等
     * @param sheetNo       sheet頁(yè)號(hào)狰住,從0開(kāi)始
     * @param headRowNum    表頭占的行數(shù),從0開(kāi)始(如果要連表頭一起讀出來(lái)則傳0)
     * @return
     */
    public static void asyncRead(File file, AnalysisEventListener<T> excelListener, Integer sheetNo, Integer headRowNum) {
        EasyExcelFactory.read(file, excelListener).sheet(sheetNo).headRowNumber(headRowNum).doRead();
    }

    /**
     * 異步無(wú)模型讀(指定sheet和表頭占的行數(shù))
     *
     * @param filePath
     * @param excelListener 監(jiān)聽(tīng)器齿梁,在監(jiān)聽(tīng)器中可以處理行數(shù)據(jù)LinkedHashMap,表頭數(shù)據(jù),異常處理等
     * @param sheetNo       sheet頁(yè)號(hào)勺择,從0開(kāi)始
     * @param headRowNum    表頭占的行數(shù)创南,從0開(kāi)始(如果要連表頭一起讀出來(lái)則傳0)
     * @return
     */
    public static void asyncRead(String filePath, AnalysisEventListener<T> excelListener, Integer sheetNo, Integer headRowNum) {
        EasyExcelFactory.read(filePath, excelListener).sheet(sheetNo).headRowNumber(headRowNum).doRead();
    }

    /**
     * 異步按模型讀取(默認(rèn)讀取sheet0,從第2行開(kāi)始讀)
     *
     * @param filePath
     * @param excelListener 監(jiān)聽(tīng)器省核,在監(jiān)聽(tīng)器中可以處理行數(shù)據(jù)LinkedHashMap稿辙,表頭數(shù)據(jù),異常處理等
     * @param clazz         模型的類類型(excel數(shù)據(jù)會(huì)按該類型轉(zhuǎn)換成對(duì)象)
     */
    public static void asyncReadModel(String filePath, AnalysisEventListener<T> excelListener, Class clazz) {
        EasyExcelFactory.read(filePath, clazz, excelListener).sheet().doRead();
    }

    /**
     * 異步按模型讀绕摇(默認(rèn)表頭占一行邻储,從第2行開(kāi)始讀)
     *
     * @param filePath
     * @param excelListener 監(jiān)聽(tīng)器,在監(jiān)聽(tīng)器中可以處理行數(shù)據(jù)LinkedHashMap旧噪,表頭數(shù)據(jù)吨娜,異常處理等
     * @param clazz         模型的類類型(excel數(shù)據(jù)會(huì)按該類型轉(zhuǎn)換成對(duì)象)
     * @param sheetNo       sheet頁(yè)號(hào),從0開(kāi)始
     */
    public static void asyncReadModel(String filePath, AnalysisEventListener<T> excelListener, Class clazz, Integer sheetNo) {
        EasyExcelFactory.read(filePath, clazz, excelListener).sheet(sheetNo).doRead();
    }

    /**
     * 異步按模型讀取
     *
     * @param inputStream
     * @param excelListener 監(jiān)聽(tīng)器淘钟,在監(jiān)聽(tīng)器中可以處理行數(shù)據(jù)LinkedHashMap宦赠,表頭數(shù)據(jù),異常處理等
     * @param clazz         模型的類類型(excel數(shù)據(jù)會(huì)按該類型轉(zhuǎn)換成對(duì)象)
     * @param sheetNo       sheet頁(yè)號(hào)米母,從0開(kāi)始
     * @param headRowNum    表頭占的行數(shù)勾扭,從0開(kāi)始(如果要連表頭一起讀出來(lái)則傳0)
     */
    public static void asyncReadModel(InputStream inputStream, AnalysisEventListener<T> excelListener, Class clazz, Integer sheetNo, Integer headRowNum) {
        EasyExcelFactory.read(inputStream, clazz, excelListener).sheet(sheetNo).headRowNumber(headRowNum).doRead();
    }

    /**
     * 異步按模型讀取
     *
     * @param file
     * @param excelListener 監(jiān)聽(tīng)器,在監(jiān)聽(tīng)器中可以處理行數(shù)據(jù)LinkedHashMap铁瞒,表頭數(shù)據(jù)妙色,異常處理等
     * @param clazz         模型的類類型(excel數(shù)據(jù)會(huì)按該類型轉(zhuǎn)換成對(duì)象)
     * @param sheetNo       sheet頁(yè)號(hào),從0開(kāi)始
     * @param headRowNum    表頭占的行數(shù)慧耍,從0開(kāi)始(如果要連表頭一起讀出來(lái)則傳0)
     */
    public static void asyncReadModel(File file, AnalysisEventListener<T> excelListener, Class clazz, Integer sheetNo, Integer headRowNum) {
        EasyExcelFactory.read(file, clazz, excelListener).sheet(sheetNo).headRowNumber(headRowNum).doRead();
    }

    /**
     * 異步按模型讀取
     *
     * @param filePath
     * @param excelListener 監(jiān)聽(tīng)器身辨,在監(jiān)聽(tīng)器中可以處理行數(shù)據(jù)LinkedHashMap,表頭數(shù)據(jù)蜂绎,異常處理等
     * @param clazz         模型的類類型(excel數(shù)據(jù)會(huì)按該類型轉(zhuǎn)換成對(duì)象)
     * @param sheetNo       sheet頁(yè)號(hào)栅表,從0開(kāi)始
     * @param headRowNum    表頭占的行數(shù),從0開(kāi)始(如果要連表頭一起讀出來(lái)則傳0)
     */
    public static void asyncReadModel(String filePath, AnalysisEventListener<T> excelListener, Class clazz, Integer sheetNo, Integer headRowNum) {
        EasyExcelFactory.read(filePath, clazz, excelListener).sheet(sheetNo).headRowNumber(headRowNum).doRead();
    }

    /**
     * 無(wú)模板寫文件
     *
     * @param filePath
     * @param head     表頭數(shù)據(jù)
     * @param data     表內(nèi)容數(shù)據(jù)
     */
    public static void write(String filePath, List<List<String>> head, List<List<Object>> data) {
        EasyExcel.write(filePath).head(head).sheet().doWrite(data);
    }

    /**
     * 無(wú)模板寫文件
     *
     * @param filePath
     * @param head      表頭數(shù)據(jù)
     * @param data      表內(nèi)容數(shù)據(jù)
     * @param sheetNo   sheet頁(yè)號(hào)师枣,從0開(kāi)始
     * @param sheetName sheet名稱
     */
    public static void write(String filePath, List<List<String>> head, List<List<Object>> data, Integer sheetNo, String sheetName) {
        EasyExcel.write(filePath).head(head).sheet(sheetNo, sheetName).doWrite(data);
    }

    /**
     * 根據(jù)excel模板文件寫入文件
     *
     * @param filePath
     * @param templateFileName
     * @param headClazz
     * @param data
     */
    public static void writeTemplate(String filePath, String templateFileName, Class headClazz, List data) {
        EasyExcel.write(filePath, headClazz).withTemplate(templateFileName).sheet().doWrite(data);
    }

    /**
     * 根據(jù)excel模板文件寫入文件
     *
     * @param filePath
     * @param templateFileName
     * @param data
     */
    public static void writeTemplate(String filePath, String templateFileName, List data) {
        EasyExcel.write(filePath).withTemplate(templateFileName).sheet().doWrite(data);
    }

    /**
     * 按模板寫文件
     *
     * @param filePath
     * @param headClazz 表頭模板
     * @param data      數(shù)據(jù)
     */
    public static void write(String filePath, Class headClazz, List data) {
        EasyExcel.write(filePath, headClazz).sheet().doWrite(data);
    }

    /**
     * 按模板寫文件
     *
     * @param filePath
     * @param headClazz 表頭模板
     * @param data      數(shù)據(jù)
     * @param sheetNo   sheet頁(yè)號(hào)怪瓶,從0開(kāi)始
     * @param sheetName sheet名稱
     */
    public static void write(String filePath, Class headClazz, List data, Integer sheetNo, String sheetName) {
        EasyExcel.write(filePath, headClazz).sheet(sheetNo, sheetName).doWrite(data);
    }

    /**
     * 按模板寫文件
     *
     * @param filePath
     * @param headClazz    表頭模板
     * @param data         數(shù)據(jù)
     * @param writeHandler 自定義的處理器,比如設(shè)置table樣式践美,設(shè)置超鏈接洗贰、單元格下拉框等等功能都可以通過(guò)這個(gè)實(shí)現(xiàn)(需要注冊(cè)多個(gè)則自己通過(guò)鏈?zhǔn)饺フ{(diào)用)
     * @param sheetNo      sheet頁(yè)號(hào),從0開(kāi)始
     * @param sheetName    sheet名稱
     */
    public static void write(String filePath, Class headClazz, List data, WriteHandler writeHandler, Integer sheetNo, String sheetName) {
        EasyExcel.write(filePath, headClazz).registerWriteHandler(writeHandler).sheet(sheetNo, sheetName).doWrite(data);
    }

    /**
     * 按模板寫文件(包含某些字段)
     *
     * @param filePath
     * @param headClazz   表頭模板
     * @param data        數(shù)據(jù)
     * @param includeCols 過(guò)濾包含的字段陨倡,根據(jù)字段名稱過(guò)濾
     * @param sheetNo     sheet頁(yè)號(hào)敛滋,從0開(kāi)始
     * @param sheetName   sheet名稱
     */
    public static void writeInclude(String filePath, Class headClazz, List data, Set<String> includeCols, Integer sheetNo, String sheetName) {
        EasyExcel.write(filePath, headClazz).includeColumnFiledNames(includeCols).sheet(sheetNo, sheetName).doWrite(data);
    }

    /**
     * 按模板寫文件(排除某些字段)
     *
     * @param filePath
     * @param headClazz   表頭模板
     * @param data        數(shù)據(jù)
     * @param excludeCols 過(guò)濾排除的字段,根據(jù)字段名稱過(guò)濾
     * @param sheetNo     sheet頁(yè)號(hào)兴革,從0開(kāi)始
     * @param sheetName   sheet名稱
     */
    public static void writeExclude(String filePath, Class headClazz, List data, Set<String> excludeCols, Integer sheetNo, String sheetName) {
        EasyExcel.write(filePath, headClazz).excludeColumnFiledNames(excludeCols).sheet(sheetNo, sheetName).doWrite(data);
    }




    /**
     * 多個(gè)sheet頁(yè)的數(shù)據(jù)鏈?zhǔn)綄懭?     * ExcelUtil.writeWithSheets(outputStream)
     * .writeModel(ExcelModel.class, excelModelList, "sheetName1")
     * .write(headData, data,"sheetName2")
     * .finish();
     *
     * @param outputStream
     * @return
     */
    public static EasyExcelWriterFactory writeWithSheets(OutputStream outputStream) {
        EasyExcelWriterFactory excelWriter = new EasyExcelWriterFactory(outputStream);
        return excelWriter;
    }

    /**
     * 多個(gè)sheet頁(yè)的數(shù)據(jù)鏈?zhǔn)綄懭?     * ExcelUtil.writeWithSheets(file)
     * .writeModel(ExcelModel.class, excelModelList, "sheetName1")
     * .write(headData, data,"sheetName2")
     * .finish();
     *
     * @param file
     * @return
     */
    public static EasyExcelWriterFactory writeWithSheets(File file) {
        EasyExcelWriterFactory excelWriter = new EasyExcelWriterFactory(file);
        return excelWriter;
    }

    /**
     * 多個(gè)sheet頁(yè)的數(shù)據(jù)鏈?zhǔn)綄懭?     * ExcelUtil.writeWithSheets(filePath)
     * .writeModel(ExcelModel.class, excelModelList, "sheetName1")
     * .write(headData, data,"sheetName2")
     * .finish();
     *
     * @param filePath
     * @return
     */
    public static EasyExcelWriterFactory writeWithSheets(String filePath) {
        EasyExcelWriterFactory excelWriter = new EasyExcelWriterFactory(filePath);
        return excelWriter;
    }

    /**
     * 多個(gè)sheet頁(yè)的數(shù)據(jù)鏈?zhǔn)綄懭耄ㄊ×藭?huì)返回一個(gè)有部分?jǐn)?shù)據(jù)的Excel)
     * ExcelUtil.writeWithSheets(response, exportFileName)
     * .writeModel(ExcelModel.class, excelModelList, "sheetName1")
     * .write(headData, data,"sheetName2")
     * .finish();
     *
     * @param response
     * @param exportFileName 導(dǎo)出的文件名稱
     * @return
     */
    public static EasyExcelWriterFactory writeWithSheetsWeb(HttpServletResponse response, String exportFileName) throws IOException {
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        // 這里URLEncoder.encode可以防止中文亂碼
        String fileName = URLEncoder.encode(exportFileName, "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
        EasyExcelWriterFactory excelWriter = new EasyExcelWriterFactory(response.getOutputStream());
        return excelWriter;
    }
}
public class EasyExcelWriterFactory {
    private int sheetNo = 0;
    private ExcelWriter excelWriter = null;

    public EasyExcelWriterFactory(OutputStream outputStream) {
        excelWriter = EasyExcel.write(outputStream).build();
    }

    public EasyExcelWriterFactory(File file) {
        excelWriter = EasyExcel.write(file).build();
    }

    public EasyExcelWriterFactory(String filePath) {
        excelWriter = EasyExcel.write(filePath).build();
    }

    /**
     * 鏈?zhǔn)侥0灞眍^寫入
     *
     * @param headClazz 表頭格式
     * @param data      數(shù)據(jù) List<ExcelModel> 或者List<List<Object>>
     * @return
     */
    public EasyExcelWriterFactory writeModel(Class headClazz, List data, String sheetName) {
        excelWriter.write(data, EasyExcel.writerSheet(this.sheetNo++, sheetName).head(headClazz).build());
        return this;
    }

    /**
     * 鏈?zhǔn)阶远x表頭寫入
     *
     * @param head
     * @param data      數(shù)據(jù) List<ExcelModel> 或者List<List<Object>>
     * @param sheetName
     * @return
     */
    public EasyExcelWriterFactory write(List<List<String>> head, List data, String sheetName) {
        excelWriter.write(data, EasyExcel.writerSheet(this.sheetNo++, sheetName).head(head).build());
        return this;
    }

    public void finish() {
        excelWriter.finish();
    }
}
public class FileUtil {


    public static InputStream getResourcesFileInputStream(String fileName) {
        return Thread.currentThread().getContextClassLoader().getResourceAsStream("" + fileName);
    }

    public static String getPath() {
        return FileUtil.class.getResource("/").getPath();
    }

    public static File createNewFile(String pathName) {
        File file = new File(getPath() + pathName);
        if (file.exists()) {
            file.delete();
        } else {
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
        }
        return file;
    }

    public static File readFile(String pathName) {
        return new File(getPath() + pathName);
    }

}

2.使用

@Data
public class DemoData {
    @ExcelProperty(value = "stringTitle",index =0)
    private String string;
    @ExcelProperty(value = "dateTitle",index =1)
    private String date;
    @ExcelProperty(value = "stringTitle",index =2)
    private String doubleData;
}
@Controller
public class ExcelController {
    private static final Logger log = LogManager.getLogger(ExcelController.class);


    /**
     * 用戶導(dǎo)入Excel
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    @ResponseBody
    public CommonResponse<?> importExcel(@RequestParam(value = "uploadFile", required = false) MultipartFile file) {
        try {
            List<DemoData> excelModelList = EasyExcelUtil.syncReadModel(file.getInputStream(), DemoData.class);
            return CommonResponse.success(excelModelList);
        } catch (IOException e) {
            log.error("Excel導(dǎo)入失敗", e);
        }
        return CommonResponse.failure("失敗");
    }


    /**
     * 導(dǎo)出Excel
     */
    @RequestMapping(value = "/download")
    @ResponseBody
    public void writeExcel(HttpServletResponse response) throws IOException {
        //初始化模擬數(shù)據(jù)
        List<DemoData> excelModelList = new ArrayList<>();
        for (int i = 0; i < 700; i++) {
            DemoData excelModel = new DemoData();
            excelModel.setString("ihuaben" + i);
            excelModel.setDate("2020-1-3");
            excelModel.setDoubleData(i + "");
            excelModelList.add(excelModel);
        }

        EasyExcelWriterFactory ihuaben = EasyExcelUtil.writeWithSheetsWeb(response, "ihuaben");
        ihuaben.writeModel(DemoData.class, excelModelList, "ihuaben");
        ihuaben.finish();
    }

    /**
     * 讀取resources下靜態(tài)模板
     */
    @RequestMapping(value = "/staticTemplate")
    @ResponseBody
    public CommonResponse<?> staticTemplate(HttpServletResponse response) {

        String fileName = FileUtil.getPath() + "static" + File.separator + "demo.xlsx";

        List<DemoData> excelModelList = EasyExcelUtil.syncReadModel(fileName, DemoData.class);
        return CommonResponse.success(excelModelList);
    }
}
接口測(cè)試
image.png

1.importExcel


image.png

2.download


image.png

3.staticTemplate
image.png

image.png
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末绎晃,一起剝皮案震驚了整個(gè)濱河市蜜唾,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌庶艾,老刑警劉巖袁余,帶你破解...
    沈念sama閱讀 221,576評(píng)論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異咱揍,居然都是意外死亡颖榜,警方通過(guò)查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,515評(píng)論 3 399
  • 文/潘曉璐 我一進(jìn)店門煤裙,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)掩完,“玉大人,你說(shuō)我怎么就攤上這事硼砰∏遗睿” “怎么了?”我有些...
    開(kāi)封第一講書(shū)人閱讀 168,017評(píng)論 0 360
  • 文/不壞的土叔 我叫張陵夺刑,是天一觀的道長(zhǎng)缅疟。 經(jīng)常有香客問(wèn)我,道長(zhǎng)遍愿,這世上最難降的妖魔是什么存淫? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 59,626評(píng)論 1 296
  • 正文 為了忘掉前任,我火速辦了婚禮沼填,結(jié)果婚禮上桅咆,老公的妹妹穿的比我還像新娘。我一直安慰自己坞笙,他們只是感情好岩饼,可當(dāng)我...
    茶點(diǎn)故事閱讀 68,625評(píng)論 6 397
  • 文/花漫 我一把揭開(kāi)白布。 她就那樣靜靜地躺著薛夜,像睡著了一般籍茧。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上梯澜,一...
    開(kāi)封第一講書(shū)人閱讀 52,255評(píng)論 1 308
  • 那天寞冯,我揣著相機(jī)與錄音,去河邊找鬼晚伙。 笑死吮龄,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的咆疗。 我是一名探鬼主播漓帚,決...
    沈念sama閱讀 40,825評(píng)論 3 421
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼午磁!你這毒婦竟也來(lái)了尝抖?” 一聲冷哼從身側(cè)響起毡们,我...
    開(kāi)封第一講書(shū)人閱讀 39,729評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎牵署,沒(méi)想到半個(gè)月后漏隐,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 46,271評(píng)論 1 320
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡奴迅,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,363評(píng)論 3 340
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了挺据。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片取具。...
    茶點(diǎn)故事閱讀 40,498評(píng)論 1 352
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖扁耐,靈堂內(nèi)的尸體忽然破棺而出暇检,到底是詐尸還是另有隱情,我是刑警寧澤婉称,帶...
    沈念sama閱讀 36,183評(píng)論 5 350
  • 正文 年R本政府宣布块仆,位于F島的核電站,受9級(jí)特大地震影響王暗,放射性物質(zhì)發(fā)生泄漏悔据。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,867評(píng)論 3 333
  • 文/蒙蒙 一俗壹、第九天 我趴在偏房一處隱蔽的房頂上張望科汗。 院中可真熱鬧,春花似錦绷雏、人聲如沸头滔。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 32,338評(píng)論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)坤检。三九已至,卻和暖如春期吓,著一層夾襖步出監(jiān)牢的瞬間早歇,已是汗流浹背。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 33,458評(píng)論 1 272
  • 我被黑心中介騙來(lái)泰國(guó)打工膘婶, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留缺前,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 48,906評(píng)論 3 376
  • 正文 我出身青樓悬襟,卻偏偏與公主長(zhǎng)得像衅码,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子脊岳,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,507評(píng)論 2 359