使用EasyPoi快速实现Excel的导入导出

excel.jpg

近期完成了后管系统报表的导入导出,完成之后做下总结

1、首先我们对采用的插件进行了筛选,最后选择EasyPoi,用的人也很多,算是对poi的简单封装

这里项目用的springboot,所以只用pom引入配置即可

        <dependency>
            <groupId>cn.afterturn</groupId>
            <artifactId>easypoi-base</artifactId>
            <version>3.0.3</version>
        </dependency>
        <dependency>
            <groupId>cn.afterturn</groupId>
            <artifactId>easypoi-web</artifactId>
            <version>3.0.3</version>
        </dependency>
        <dependency>
            <groupId>cn.afterturn</groupId>
            <artifactId>easypoi-annotation</artifactId>
            <version>3.0.3</version>
        </dependency>

2、根据配置编写实体类

先简单介绍一下关于@Excel注解的一些常用属性
name:列名
orderNum:第几列
replace:值得替换 例:replace = {"身份证_1"} 数据库值为"1",导出时会自动被"身份证"代替

    @Excel(name = "姓名", orderNum = "0")
    private String name;
    @Excel(name = "证件类型", replace = {"身份证_1"}, orderNum = "1")
    private String identifyType;
    @Excel(name = "证件号码", orderNum = "2")
    private String identifyNo;
    @Excel(name = "手机号1", orderNum = "3")
    private String phoneA;
    @Excel(name = "手机号2", orderNum = "4")
    private String phoneB;
    @Excel(name = "手机号3", orderNum = "5")
    private String phoneC;
    @Excel(name = "固定电话", orderNum = "6")
    private String telephone;
    @Excel(name = "电子邮箱", orderNum = "7")
    private String email;
    @Excel(name = "身份证地址", orderNum = "8")
    private String idcardAdress;
    @Excel(name = "户籍地址", orderNum = "9")
    private String householdAddress;
    @Excel(name = "居住地址", orderNum = "10")
    private String liveAddress;
    @Excel(name = "工作地址", orderNum = "11")
    private String workAddress;

3、整合导入导出方法

package com.***.common;

import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import org.apache.commons.lang.StringUtils;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

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;

public class FileWithExcelUtil {
    private static final Logger log = LoggerFactory.getLogger(FileWithExcelUtil .class);
    public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass,String fileName,boolean isCreateHeader, HttpServletResponse response){
        ExportParams exportParams = new ExportParams(title, sheetName);
        exportParams.setCreateHeadRows(isCreateHeader);
        defaultExport(list, pojoClass, fileName, response, exportParams);

    }
    public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass,String fileName, HttpServletResponse response){
        defaultExport(list, pojoClass, fileName, response, new ExportParams(title, sheetName));
    }
    public static void exportExcel(List<Map<String, Object>> list, String fileName, HttpServletResponse response){
        defaultExport(list, fileName, response);
    }

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

    private static void downLoadExcel(String fileName, HttpServletResponse response, Workbook workbook) {
        try {
            response.setCharacterEncoding("UTF-8");
            response.setHeader("content-Type", "application/vnd.ms-excel");
            response.setHeader("Content-Disposition",
                    "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            workbook.write(response.getOutputStream());
        } catch (IOException e) {
            log.error("[monitor][IO][表单功能]", e);
        }
    }
    private static void defaultExport(List<Map<String, Object>> list, String fileName, HttpServletResponse response) {
        Workbook workbook = ExcelExportUtil.exportExcel(list, ExcelType.HSSF);
        if (workbook != null);
        downLoadExcel(fileName, response, workbook);
    }

    public static <T> List<T> importExcel(String filePath,Integer titleRows,Integer headerRows, Class<T> pojoClass){
        if (StringUtils.isBlank(filePath)){
            return null;
        }
        ImportParams params = new ImportParams();
        params.setTitleRows(titleRows);
        params.setHeadRows(headerRows);
        List<T> list = null;
        try {
            list = ExcelImportUtil.importExcel(new File(filePath), pojoClass, params);
        }catch (NoSuchElementException e){
            throw e;
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
        return list;
    }
    public static <T> List<T> importExcel(MultipartFile file, Integer titleRows, Integer headerRows, Class<T> pojoClass){
        if (file == null){
            return null;
        }
        ImportParams params = new ImportParams();
        params.setTitleRows(titleRows);
        params.setHeadRows(headerRows);
        List<T> list = null;
        try {
            list = ExcelImportUtil.importExcel(file.getInputStream(), pojoClass, params);
        }catch (NoSuchElementException e){
            throw e;
        } catch (Exception e) {
            e.printStackTrace();
            log.error("[monitor][表单功能]", e);
        }
        return list;
    }

}

4、导出操作

/**
     * 导出模版
     * @param response
     */
    @RequestMapping("/exportExcel/model")
    public ResponseModel export(HttpServletResponse response){
       try {
            //模拟从数据库获取需要导出的数据
            List<CustomerList> personList = new ArrayList<>();
            FileWithExcelUtil.exportExcel(personList,"客户信息表","客户表",CustomerList.class,"客户表.xls",response);
            return ResponseModel.success("操作成功");
        } catch (Exception e) {
            logger.info("getCustomerPage", e);
            return ResponseModel.fail("导出模版失败");
            // TODO: handle exception
        }
      
    }

5、导入操作

将导入的模版数据拿到,填充到自己要使用的实体类
ps:导入的数据模版一般都是平铺的,而我们的实体类一般都有层次,所以我们的excel模版实体往往不是我们数据库对应的bean,需要我们将其自行填充

/**
     * 导入excel
     */
    @RequestMapping(value = "/importExcelForType", method = RequestMethod.POST)
    public ResponseModel importExcel(@RequestParam("file") MultipartFile file,String customerType){
        try {
//          String filePath = "/Users/***/Downloads/response.xls";
            //解析excel,
//          List<CustomerList> personList = FileWithExcelUtil.importExcel(filePath, 1, 1, CustomerList.class);
            List<CustomerList> personList = FileWithExcelUtil.importExcel(file, 1, 1, CustomerList.class);
            //也可以使用MultipartFile,使用 FileUtil.importExcel(MultipartFile file, Integer titleRows, Integer headerRows, Class<T> pojoClass)导入
            System.out.println("导入数据一共【"+personList.size()+"】行");
            
            for (int i = 0; i < personList.size(); i++) {
                CustomerList excel = personList.get(i);
                CmCustomerForExcel customer =  customerListByExcel(excel);
                customer.setCustomerType(customerType);
                customerService.saveExcelList(customer);
            }
            logger.info(personList.toString());
            return ResponseModel.success("操作成功");
            
        } catch (Exception e) {
            // TODO: handle exception
            logger.error(e.toString());
            return ResponseModel.fail("导入失败");
        }
    

补充

高级用法可参考EasyPoi的官方文档:http://easypoi.mydoc.io

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,736评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,167评论 1 291
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,442评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,902评论 0 204
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,302评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,573评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,847评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,562评论 0 197
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,260评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,531评论 2 245
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,021评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,367评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,016评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,068评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,827评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,610评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,514评论 2 269