Spring Boot2 集成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();
        }
    }


}

请求样例

猜你喜欢

转载自blog.csdn.net/lovelichao12/article/details/103123677
今日推荐