Springboot+Easypoi 实现excel导入导出

前言:
开发中经常会遇到excel的处理,导入导出解析等等,java中比较流行的用poi,但是每次都要写大段工具类来搞定这事儿,此处推荐一个别人造好的轮子【easypoi】,下面介绍下“轮子”的使用(以导入、导出Excel到实体类为例)。

详细用法,可参考EasyPoi参考文档:http://easypoi.mydoc.io/#text_186900

pom引入


        org.springframework.boot
        spring-boot-starter-parent
        2.1.3.RELEASE
         
    

    
        
            org.springframework.boot
            spring-boot-starter-web
            2.1.3.RELEASE
        
        
        
            cn.afterturn
            easypoi-base
            3.2.0
        
        
            cn.afterturn
            easypoi-web
            3.2.0
        
        
            cn.afterturn
            easypoi-annotation
            3.2.0
        

    

编写实体类

此处注意必须要有空构造函数,否则会报错“对象创建错误”

package com.dengzhili;

import cn.afterturn.easypoi.excel.annotation.Excel;

import java.io.Serializable;
import java.util.Date;

/**
 * describe:
 *
 * @author dengzl
 * @date 2019/06/10
 */
public class Goods implements Serializable {

    //未添加@Excel注解,不解析
    private String id;

    //商品编号,主键(Integer类型的取值)
    @Excel(name = "NO",width = 20)
    private Integer no;
    //商品名称(String类型的取值)
    @Excel(name = "商品名称",width = 20)
    private String name;
    //1 食品 2 服装 3 酒水 4 花卉
    //商品所属类别(Integer类型的取值,对应的数值要转成相应的文字)
    @Excel(name = "商品类别",width = 20)
    private Integer type;
    //商品保质器(测试日期值得获取)
    @Excel(name = "保质期",width = 20,exportFormat = "yyyy-MM-dd")
    private Date shelfLife;
    //库存是否还有?0 无 1有(测试Integer类型的三目运算)
    @Excel(name = "库存是否还有",width = 20)
    private Integer isHave;

    //该商品是否经过了审核"0" 未过,"1" 通过(测试String类型的三目运算)
    //未添加@Excel注解,不解析
    private String  isAudit;

    public Integer getNo() {
        return no;
    }

    public void setNo(Integer no) {
        this.no = no;
    }

    public String getName() {
        return name;
    }

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

    public Integer getType() {
        return type;
    }

    public void setType(Integer type) {
        this.type = type;
    }

    public Date getShelfLife() {
        return shelfLife;
    }

    public void setShelfLife(Date shelfLife) {
        this.shelfLife = shelfLife;
    }

    public Integer getIsHave() {
        return isHave;
    }

    public void setIsHave(Integer isHave) {
        this.isHave = isHave;
    }

    public String getIsAudit() {
        return isAudit;
    }

    public void setIsAudit(String isAudit) {
        this.isAudit = isAudit;
    }

    public String getId() {
        return id;
    }

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

    public Goods() {
    }

    public Goods(Integer no, String name, Integer type, Date shelfLife, Integer isHave, String isAudit) {
        this.no = no;
        this.name = name;
        this.type = type;
        this.shelfLife = shelfLife;
        this.isHave = isHave;
        this.isAudit = isAudit;
    }

    @Override
    public String toString() {
        return "Goods{" +
                "id='" + id + '\'' +
                ", no=" + no +
                ", name='" + name + '\'' +
                ", type=" + type +
                ", shelfLife=" + shelfLife +
                ", isHave=" + isHave +
                ", isAudit='" + isAudit + '\'' +
                '}';
    }
}

Controller层代码

package com.dengzhili;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * describe:
 *
 * @author dengzl
 * @date 2019/06/10
 */
@RestController
public class EasyPOIController {

    @RequestMapping("/exportExcel")
    public void export(HttpServletResponse response) throws Exception {
        //模拟数据库数据
        Goods goods1 = new Goods(110, "苹果", 1, new Date(), 0, "1");
        Goods goods2 = new Goods(111, "格子衫", 2, new Date(), 0, "0");
        Goods goods3 = new Goods(112, "拉菲红酒", 3, new Date(), 1, "1");
        Goods goods4 = new Goods(113, "玫瑰", 4, new Date(), 1, "0");

        List goodsList = new ArrayList();
        goodsList.add(goods1);
        goodsList.add(goods2);
        goodsList.add(goods3);
        goodsList.add(goods4);

        for (Goods goods : goodsList) {
            System.out.println(goods);
        }
        //导出
        FileUtil.exportExcel(goodsList,Goods.class,"商品.xls",response);
    }

    @RequestMapping("/importExcel")
    public void importExcel() throws NormalException {
        //本地文件 模拟文件上传解析
        String filePath = "/Users/dengzhili/Downloads/商品.xls";
        //解析excel
        List goodsList = FileUtil.importExcel(filePath,0,1,Goods.class);
        //也可以使用MultipartFile,使用 FileUtil.importExcel(MultipartFile file, Integer titleRows, Integer headerRows, Class pojoClass)导入
        System.out.println("导入数据一共【"+goodsList.size()+"】行");

        //TODO 保存数据库
        for (Goods goods:goodsList) {
            System.out.println(goods);
        }
    }
}

导入导出工具类

package com.dengzhili;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;

/**
 * describe:
 *
 * @author dengzl
 * @date 2019/06/10
 */
public class FileUtil {

    public static void exportExcel(List list, String title, String sheetName, Class pojoClass, String fileName, boolean isCreateHeader, HttpServletResponse response) throws NormalException {
        ExportParams exportParams = new ExportParams(title, sheetName);
        exportParams.setCreateHeadRows(isCreateHeader);
        defaultExport(list, pojoClass, fileName, response, exportParams);
    }
    public static void exportExcel(List list, Class pojoClass, String fileName,  HttpServletResponse response) throws NormalException {
        ExportParams exportParams = new ExportParams();
        defaultExport(list, pojoClass, fileName, response, exportParams);
    }
    public static void exportExcel(List list, String title, String sheetName, Class pojoClass,String fileName, HttpServletResponse response) throws NormalException {
        defaultExport(list, pojoClass, fileName, response, new ExportParams(title, sheetName));
    }
    public static void exportExcel(List> list, String fileName, HttpServletResponse response) throws NormalException {
        defaultExport(list, fileName, response);
    }

    private static void defaultExport(List list, Class pojoClass, String fileName, HttpServletResponse response, ExportParams exportParams) throws NormalException {
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams,pojoClass,list);
        if (workbook != null);
        downLoadExcel(fileName, response, workbook);
    }

    private static void downLoadExcel(String fileName, HttpServletResponse response, Workbook workbook) throws NormalException {
        OutputStream outputStream=null;
        try {
            response.setCharacterEncoding("UTF-8");
            response.setHeader("content-Type", "application/vnd.ms-excel");
            response.setHeader("Content-Disposition",
                    "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            outputStream = response.getOutputStream();

            workbook.write(outputStream);
        } catch (IOException e) {
            throw new NormalException(e.getMessage());
        }finally {
            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    private static void defaultExport(List> list, String fileName, HttpServletResponse response) throws NormalException {
        Workbook workbook = ExcelExportUtil.exportExcel(list, ExcelType.HSSF);
        if (workbook != null);
        downLoadExcel(fileName, response, workbook);
    }

    public static  List importExcel(String filePath,Integer titleRows,Integer headerRows, Class pojoClass) throws NormalException {
        if (StringUtils.isBlank(filePath)){
            return null;
        }
        ImportParams params = new ImportParams();
        params.setTitleRows(titleRows);
        params.setHeadRows(headerRows);
        List list = null;
        try {
            list = ExcelImportUtil.importExcel(new File(filePath), pojoClass, params);
        }catch (NoSuchElementException e){
            throw new NormalException("模板不能为空");
        } catch (Exception e) {
            e.printStackTrace();
            throw new NormalException(e.getMessage());
        }
        return list;
    }
    public static  List importExcel(MultipartFile file, Integer titleRows, Integer headerRows, Class pojoClass) throws NormalException {
        if (file == null){
            return null;
        }
        ImportParams params = new ImportParams();
        params.setTitleRows(titleRows);
        params.setHeadRows(headerRows);
        List list = null;
        try {
            list = ExcelImportUtil.importExcel(file.getInputStream(), pojoClass, params);
        }catch (NoSuchElementException e){
            throw new NormalException("excel文件不能为空");
        } catch (Exception e) {
            throw new NormalException(e.getMessage());
        }
        return list;
    }
}

启动类

package com.dengzhili;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * describe:
 *
 * @author dengzl
 * @date 2019/06/10
 */
@SpringBootApplication
public class AppMain {

    public static void main(String[] args) {
        SpringApplication.run(AppMain.class);
    }
}

测试

访问 http://localhost:8080/exportExcel
浏览器自动下载Excel文件,内容如下

image.png

访问http://localhost:8080/importExcel,模拟文件上传,打印如下:

image.png

你可能感兴趣的:(Springboot+Easypoi 实现excel导入导出)