Spring Boot 集成Easyexcel實現excel導入導出

在管理一個系統時,總會有許多的數據以及功能,當然也少不了Excel的導入/導出,實現這個導入/導出Excel的功能也不復雜,完全使用第三方的類庫即可實現。

技術選型

能夠實現導入/導出Excel的第三方常用類庫有 Apache poi、Java Excel(JXL)和阿里巴巴開源的 Easyexcel 等。這麼多類庫該怎麼選呢?在這裏我給大家推薦阿里巴巴開源的Easyexcel。

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

性能對比

poi 和 jxl 對內存的消耗很大,在處理大批量的數據時,容易造成內存溢出。比如處理一個 3M 的 Excel,poi 和 jxl 可能需要上百兆的內存,但 easyexcel 可能只需要幾百或幾千 KB(內存消耗對比有些誇張)。在性能這一塊,Excel 完全是秒殺 poi 和 jxl。

學習複雜度對比

我最開始使用的是 poi。在學習它的時候,理解起來不難,就是操作的時候太難了。因爲 poi 需要自己處理數據,還有複雜的表格樣式,就光是處理數據這一款就很頭疼了。等你寫好所有的代碼,沒有幾百行,你是實現不了的。反觀 easyexcel。它能自己處理數據,表格格式也簡單,即使是小白也很容易上手,在學習複雜的這塊也秒殺 poi、 jxl 。

項目結構

pom.xml

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

ExcelListener

package com.example.esb.base.listener;

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

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

/**
 * @Auther: lc
 * @Date: 2019/11/17 16:11
 * @Description:
 */
public class ExcelListener extends AnalysisEventListener {

    //可以通過實例獲取該值
    private List<Object> datas = new ArrayList<Object>();
    public void invoke(Object o, AnalysisContext analysisContext) {
        datas.add(o);//數據存儲到list,供批量處理,或後續自己業務邏輯處理。
        doSomething(o);//根據自己業務做處理
    }

    private void doSomething(Object object) {
        //1、入庫調用接口
    }

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

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

    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        // datas.clear();//解析結束銷燬不用的資源
    }

}

PersonDto

package com.example.esb.vo;

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

/**
 * @Auther: lc
 * @Date: 2019/11/17 15:42
 * @Description: bean對象
 */
public class PersonDto extends BaseRowModel {

    /** id */
    @ExcelProperty(index = 0 , value = "id")
    private String id;
    /** 姓名 **/
    @ExcelProperty(index = 1 , value = "姓名")
    private String name;
    /** 生日 **/
    @ExcelProperty(index = 2 , value = "生日" , format = "yyyy-MM-dd")
    private String birth;

    public String getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public String getBirth() {
        return birth;
    }

    public void setId(String id) {
        this.id = id;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setBirth(String birth) {
        this.birth = birth;
    }
}

ExcelUtil工具類

/**
     * 導出 Excel :一個 sheet,帶表頭.
     * @param response  HttpServletResponse
     * @param list      數據 list,每個元素爲一個 BaseRowModel
     * @param fileName  導出的文件名
     * @param sheetName 導入文件的 sheet 名
     * @param model     映射實體類,Excel 模型
     * @throws Exception 異常
     */
    public static void writeExcel(HttpServletResponse response, List<? extends BaseRowModel> list,
            String fileName, String sheetName, BaseRowModel model) throws Exception {
        ExcelWriter writer = new ExcelWriter(getOutputStreamExcel(fileName, response), ExcelTypeEnum.XLSX);
        Sheet sheet = new Sheet(1, 0, model.getClass());
        //設置列寬 設置每列的寬度
        /*Map columnWidth = new HashMap();
        columnWidth.put(0,10000);columnWidth.put(1,40000);columnWidth.put(2,10000);columnWidth.put(3,10000);
        sheet1.setColumnWidthMap(columnWidth);*/
        // 設置自適應寬度
        sheet.setAutoWidth(Boolean.TRUE);
        sheet.setSheetName(sheetName);
        writer.write(list, sheet);
        writer.finish();
    }

    /**
     * 導出文件時爲Writer生成OutputStream.
     * @param fileName 文件名
     * @param response response
     * @return
     */
    private static OutputStream getOutputStreamExcel(String fileName,HttpServletResponse response) throws Exception {
        try {
            fileName = URLEncoder.encode(fileName, "UTF-8");
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf8");
            response.setHeader("Content-Disposition", "attachment; filename=" + fileName + ".xlsx");
            response.setHeader("Pragma", "public");
            response.setHeader("Cache-Control", "no-store");
            response.addHeader("Cache-Control", "max-age=0");
            return response.getOutputStream();
        } catch (IOException e) {
            throw new Exception("導出excel表格失敗!", e);
        }
    }

 

ExcelController

package com.example.esb.controller;

import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.fastjson.JSON;
import com.example.esb.base.listener.ExcelListener;
import com.example.esb.service.ExcleService;
import com.example.esb.vo.PersonDto;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * @Auther: lc
 * @Date: 2019/11/16 16:26
 * @Description: excel導出與導入
 */
@Api(tags="excelController")
@RestController
@RequestMapping("/excel")
@CrossOrigin
public class ExcelController {

    
    /**
     * 導入數據
     * @param file
     */
    @ApiOperation(value= "導入數據", notes= "導入數據")
    @PostMapping(value = "importExcel")
    public void importExcel(@RequestParam("file") MultipartFile file){
        try{
            InputStream inputStream = file.getInputStream();
            //實例化實現了AnalysisEventListener接口的類
            ExcelListener listener = new ExcelListener();
            //傳入參數
            ExcelReader excelReader = new ExcelReader(inputStream, ExcelTypeEnum.XLSX, null, listener);
            //讀取信息
            excelReader.read(new Sheet(1, 1, PersonDto.class));
            //獲取數據
            List<Object> list = listener.getDatas();
            List<PersonDto> lists = new ArrayList<PersonDto>();
            PersonDto catagory = new PersonDto();
            //轉換數據類型,並插入到數據庫
            for (int i = 0; i < list.size(); i++) {
                catagory = (PersonDto) list.get(i);
                lists.add(catagory);
            }
            System.out.println(JSON.toJSON(lists));
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 下載模板
     */  
    @ApiOperation(value="下載Excel模板",notes = "下載Excel模板")
    @PostMapping(value = "/downloadExcel")
    public void downloadExcel(HttpServletRequest request, HttpServletResponse response) {
        try {
            List<PersonDto> list = new ArrayList<PersonDto>();
            ExcelUtil.writeExcel(response, list, "信息", "Sheet1", new PersonDto());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}

請求樣例

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章