SpringBoot整合EasyPoi实现导入导出Excel

一、前言

平时我们写代码时常常需要一些导入导出的操作,一般都是用Apache的poi,但是发现很繁琐,总是在Copy… ,无意间发现一款简单粗暴的神器EasyPoi,导入导出很方便,而且支持多种格式的导入导出,下面介绍基于@Excel注解实现简单的导入导出Excel。

码云地址 :easypoi-spring-boot-starter
官方教程:https://easypoi.mydoc.io/


二、 功能

Excel自适应xls和xlsx两种格式,word只支持docx模式

1.Excel导入
  • 注解导入
  • Map导入
  • 大数据量导入sax模式
  • 导入文件保存
  • 文件校验
  • 字段校验

2.Excel导出

  • 注解导出
  • 模板导出
  • html导出

3.Excel转html

4.word导出

5.pdf导出

三、使用EasyPoi
1. SpringBoot项目pom.xml中添加依赖
<dependency>
     <groupId>cn.afterturn</groupId>
     <artifactId>easypoi-spring-boot-starter</artifactId>
     <version>3.2.0</version>
</dependency>
        
2. 工具类(网上很多)
package com.example.demo.utils;

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.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;

//Excel导入导出工具类
public class ExcelUtils {
    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);
    }

    /**
     *
     * @param list 数据列表
     * @param title 标题
     * @param sheetName sheet名字
     * @param pojoClass 导出对象的Class类型
     * @param fileName 文件名
     * @param response
     */
    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) {
            // throw new NormalException(e.getMessage());
        }
    }

    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 new NormalException("模板不能为空");
        } catch (Exception e) {
            e.printStackTrace();
            // throw new NormalException(e.getMessage());
        }
        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 new NormalException("excel文件不能为空");
        } catch (Exception e) {
            // throw new NormalException(e.getMessage());
            System.out.println(e.getMessage());
        }
        return list;
    }

}


3. 定义需要导出的数据类型Users ,并使用@Excel注解与excel列映射

注意:属性命名符合驼峰规范,正确:stuName 错误:STUName,我遇到一个坑就是因为命名不规范

package com.example.demo.entity;


import cn.afterturn.easypoi.excel.annotation.Excel;
import cn.afterturn.easypoi.excel.annotation.ExcelTarget;
import lombok.Data;

import java.util.Date;

/**
 * @ExcelTarget限定一个到处实体的注解, 以及一些通用设置, 作用于最外面的实体
 *
 * @Excel注解的字段表示与Excel列映射,不添加此注解不会映射
 *  name:列标题
 *  orderNum:第几列
 *  width:列宽
 *  exportFormat:日期类型格式化,可指定格式(适用于Date类型)
 *  format 时间格式,相当于同时设置了exportFormat 和 importFormat(适用于Date类型)
 *  databaseFormat: 导出时间设置,如果字段是Date类型则不需要设置 数据库如果是string 类型,这个需要设置这个数据库格式,用以转换时间格式输出(适用于String类型)
 *  replace: String[]类型,值得替换  导出是{"男_1", "女_2"} 导入反过来
 *  suffix: 文字后缀,如%  90变成90%    
 */
@ExcelTarget("20")
@Data //Lombok了解下
public class Users implements java.io.Serializable {
    @Excel(name = "序号", width = 10) //后期controller中将为id字段重新赋值,实现序号效果
    private Integer id;

    @Excel(name = "姓名", orderNum = "0", width = 30)
    private String name;

    @Excel(name = "性别", replace = {"男_1", "女_2"}, orderNum = "1", width = 30,suffix = "人")
    private String sex;

    @Excel(name = "生日", format = "yyyy-MM-dd HH:mm:ss", orderNum = "2", width = 30)
    private Date birthday;

}
4. Controller层导出方法

导出接口方法

@RestController
public class UsersController {
	//导出接口
    @GetMapping("/exportExcel")
    public void export(HttpServletResponse response) {
        System.out.println("开始导出");
        // 模拟从数据库获取需要导出的数据 (偷懒,嘻嘻!)
        List<Users> personList = getUsersList();
        //设置序号(将id字段作为序号,导出后实现序号递增)
         Integer i =1;
        for (Users users : personList) {
            users.setId(i++);
        }
        // 导出操作
        ExcelUtils.exportExcel(personList, "easypoi导出功能(用户表)", "导出sheet1", Users.class, "测试Users.xls", response);

    }


    public List<Users> getUsersList() {
        List<Users> listAll = Lists.newArrayList();
        List<Users> list = Lists.newArrayList();
        Users Users = new Users();
        Users.setId(10);
        Users.setName("张三");
        Users.setSex("1");
        Users.setBirthday(new Date());

        Users Users1 = new Users();
        Users1.setId(20);
        Users1.setName("李四");
        Users1.setSex("1");
        Users1.setBirthday(new Date());
        Users.setBirthday(new Date());

        Users Users2 = new Users();
        Users2.setId(20);
        Users2.setName("王五");
        Users2.setSex("2");
        Users2.setBirthday(new Date());

        list.add(Users);
        list.add(Users1);
        list.add(Users2);
        listAll.addAll(list);
        return listAll;
    }

}

5. Controller层导入方法

导入接口方法

@PostMapping("/importExcel")
public String importExcel2(@RequestParam("file") MultipartFile file) {
    ImportParams importParams = new ImportParams();
    // 数据处理
    //表格标题行数,默认0
    importParams.setHeadRows(1);
    //表头行数,默认1
    importParams.setTitleRows(1);
    //是否需要校验上传的Excel,默认false
    importParams.setNeedVerfiy(false);

    try {
        ExcelImportResult<Users> result = ExcelImportUtil.importExcelMore(file.getInputStream(), Users.class, importParams);
        List<Users> userList = result.getList();
        for (Users users : userList) {
            log.info("从Excel导入数据到数据库的详细为 :{}", JSONObject.toJSONString(users));
            //TODO 将导入的数据做保存数据库操作,先将所有数据id设置为null
        }
        log.info("从Excel导入数据一共 {} 行 ", userList.size());
    } catch (IOException e) {
        log.error("导入失败:{}", e.getMessage());
    } catch (Exception e1) {
        log.error("导入失败:{}", e1.getMessage());
    }
    return "导入成功";
}
四、测试导入、导出

关于启动报错:Consider renaming one of the beans or enabling overriding by setting
原因:bean名称冲突
解决方案:添加配置spring.main.allow-bean-definition-overriding=true #当遇到同样名字的时候,是否允许覆盖注册

1.测试导出
  • 浏览器访问导出接口,发现下载成功
    在这里插入图片描述
  • 打开后查看如下
    在这里插入图片描述
2.测试导入
  • PostMan测试导入
    在这里插入图片描述
  • 控制台输出,看到了导入的数据
    在这里插入图片描述

好了,以上就实现了基本的Excel导入导出功能,其他功能类似,可查阅官方文档进一步探究。
参考资料:https://blog.csdn.net/Thinkingcao/article/details/85005930

  • 12
    点赞
  • 118
    收藏
    觉得还不错? 一键收藏
  • 9
    评论
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值