springBoot excel導出 下載 超簡單


1.導入maven依賴包

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

新建以下工具類

package com.mybatis.plus.excel;

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.support.ExcelTypeEnum;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

/**
 * @Author pt
 * @Description 工具類
 * @Date 2018-06-06
 * @Time 14:07
 */
public class ExcelUtil {
    /**
     * 讀取 Excel(多個 sheet)
     *
     * @param excel    文件
     * @param rowModel 實體類映射,繼承 BaseRowModel 類
     * @return Excel 數據 list
     */
    public static List<Object> readExcel(MultipartFile excel, BaseRowModel rowModel) {
        ExcelListener excelListener = new ExcelListener();
        ExcelReader reader = getReader(excel, excelListener);
        if (reader == null) {
            return null;
        }
        for (Sheet sheet : reader.getSheets()) {
            if (rowModel != null) {
                sheet.setClazz(rowModel.getClass());
            }
            reader.read(sheet);
        }
        return excelListener.getDatas();
    }

    /**
     * 讀取某個 sheet 的 Excel
     *
     * @param excel    文件
     * @param rowModel 實體類映射,繼承 BaseRowModel 類
     * @param sheetNo  sheet 的序號 從1開始
     * @return Excel 數據 list
     */
    public static List<Object> readExcel(MultipartFile excel, BaseRowModel rowModel, int sheetNo) {
        return readExcel(excel, rowModel, sheetNo, 1);
    }

    /**
     * 讀取某個 sheet 的 Excel
     *
     * @param excel       文件
     * @param rowModel    實體類映射,繼承 BaseRowModel 類
     * @param sheetNo     sheet 的序號 從1開始
     * @param headLineNum 表頭行數,默認為1
     * @return Excel 數據 list
     */
    public static List<Object> readExcel(MultipartFile excel, BaseRowModel rowModel, int sheetNo,
                                         int headLineNum) {
        ExcelListener excelListener = new ExcelListener();
        ExcelReader reader = getReader(excel, excelListener);
        if (reader == null) {
            return null;
        }
        reader.read(new Sheet(sheetNo, headLineNum, rowModel.getClass()));
        return excelListener.getDatas();
    }

    /**
     * 導出 Excel :一個 sheet,帶表頭
     *
     * @param response  HttpServletResponse
     * @param list      數據 list,每個元素為一個 BaseRowModel
     * @param fileName  導出的文件名
     * @param sheetName 導入文件的 sheet 名
     * @param object    映射實體類,Excel 模型
     */
    public static void writeExcel(HttpServletResponse response, List<? extends BaseRowModel> list,
                                  String fileName, String sheetName, BaseRowModel object) {
        ExcelWriter writer = new ExcelWriter(getOutputStream(fileName, response), ExcelTypeEnum.XLSX);
        Sheet sheet = new Sheet(1, 0, object.getClass());
        sheet.setSheetName(sheetName);
        writer.write(list, sheet);
        writer.finish();
    }

    /**
     * 導出 Excel :多個 sheet,帶表頭
     *
     * @param response  HttpServletResponse
     * @param list      數據 list,每個元素為一個 BaseRowModel
     * @param fileName  導出的文件名
     * @param sheetName 導入文件的 sheet 名
     * @param object    映射實體類,Excel 模型
     */
    public static ExcelWriterFactroy writeExcelWithSheets(HttpServletResponse response, List<? extends BaseRowModel> list,
                                                          String fileName, String sheetName, BaseRowModel object) {
        ExcelWriterFactroy writer = new ExcelWriterFactroy(getOutputStream(fileName, response), ExcelTypeEnum.XLSX);
        Sheet sheet = new Sheet(1, 0, object.getClass());
        sheet.setSheetName(sheetName);
        writer.write(list, sheet);
        return writer;
    }

    /**
     * 導出文件時為Writer生成OutputStream
     */
    private static OutputStream getOutputStream(String fileName, HttpServletResponse response) {
        //創建本地文件
        String filePath = fileName + ".xlsx";
        File dbfFile = new File(filePath);
        try {
            if (!dbfFile.exists() || dbfFile.isDirectory()) {
                dbfFile.createNewFile();
            }
            fileName = new String(filePath.getBytes(), "ISO-8859-1");
            response.addHeader("Content-Disposition", "filename=" + fileName);
            return response.getOutputStream();
        } catch (IOException e) {
            throw new ExcelException("創建文件失敗!");
        }
    }

    /**
     * 返回 ExcelReader
     *
     * @param excel         需要解析的 Excel 文件
     * @param excelListener new ExcelListener()
     */
    private static ExcelReader getReader(MultipartFile excel,
                                         ExcelListener excelListener) {
        String filename = excel.getOriginalFilename();
        if (filename == null || (!filename.toLowerCase().endsWith(".xls") && !filename.toLowerCase().endsWith(".xlsx"))) {
            throw new ExcelException("文件格式錯誤!");
        }
        try {
            BufferedInputStream bufferedInputStream = new BufferedInputStream(excel.getInputStream());
            return new ExcelReader(bufferedInputStream, null, excelListener, false);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
package com.mybatis.plus.excel;

/**
 *
 *
 * @Author pt
 * @Description Excel 解析 Exception
 * @Date 2018-06-06
 * @Time 15:56
 */
public class ExcelException extends RuntimeException {
    public ExcelException(String message) {
        super(message);
    }
}
package com.mybatis.plus.excel;


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

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

/**
 * @Author pt
 * @Description 監聽類,可以自定義
 * @Date 2018-06-05
 * @Time 16:58
 */
public class ExcelListener extends AnalysisEventListener {

    //自定義用於暫時存儲data。
    //可以通過實例獲取該值
    private List<Object> datas = new ArrayList<>();

    /**
     * 通過 AnalysisContext 對象還可以獲取當前 sheet,當前行等數據
     */
    @Override
    public void invoke(Object object, AnalysisContext context) {
        //數據存儲到list,供批量處理,或后續自己業務邏輯處理。
        datas.add(object);
        //根據業務自行 do something
        doSomething();

        /*
        如數據過大,可以進行定量分批處理
        if(datas.size()<=100){
            datas.add(object);
        }else {
            doSomething();
            datas = new ArrayList<Object>();
        }
         */

    }

    /**
     * 根據業務自行實現該方法
     */
    private void doSomething() {
    }

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

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

    public void setDatas(List<Object> datas) {
        this.datas = datas;
    }
}
package com.mybatis.plus.excel;

import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.BaseRowModel;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.support.ExcelTypeEnum;

import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

/**
 * Created with IntelliJ IDEA
 *
 * @Author pt
 * @Description
 * @Date 2018-06-07
 * @Time 16:47
 */
public class ExcelWriterFactroy extends ExcelWriter {
    private OutputStream outputStream;
    private int sheetNo = 1;

    public ExcelWriterFactroy(OutputStream outputStream, ExcelTypeEnum typeEnum) {
        super(outputStream, typeEnum);
        this.outputStream = outputStream;
    }

    public ExcelWriterFactroy write(List<? extends BaseRowModel> list, String sheetName,
                                    BaseRowModel object) {
        this.sheetNo++;
        try {
            Sheet sheet = new Sheet(sheetNo, 0, object.getClass());
            sheet.setSheetName(sheetName);
            this.write(list, sheet);
        } catch (Exception ex) {
            ex.printStackTrace();
            try {
                outputStream.flush();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return this;
    }

    @Override
    public void finish() {
        super.finish();
        try {
            outputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

創建導出表格對應實體

package com.mybatis.plus.dto;

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

@Data
public class ExcelTestDto extends BaseRowModel {

    @ExcelProperty(value = "字典描述")
    private String dictDesc;

    @ExcelProperty(value = "字典名稱")
    private String dictName;
}

業務邏輯代碼

@RequestMapping("export")
    public String export(HttpServletResponse response){
        List<Dict> list = iDictService.list();
        List<ExcelTestDto> excelDtos = new ArrayList<>();
        for (Dict dict : list) {
            ExcelTestDto excelDto = new ExcelTestDto();
            BeanUtil.copyProperties(dict,excelDto);
            excelDtos.add(excelDto);
        }
        String key = DateUtil.format(new Date(), "yyyy-MM-dd-HH-mm-ss");
        // 配置文件下載
        response.setHeader("content-type", "application/octet-stream");
        response.setContentType("application/octet-stream");
        ExcelUtil.writeExcel(response, excelDtos, key, "sheet1", new ExcelTestDto());
        return "success";
    }

最后在瀏覽器url輸入導出接口地址 導出效果

 


免責聲明!

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



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