欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

【easypoi】 实现excel导入导出(多sheet)

程序员文章站 2022-05-17 09:26:00
...

首先导入jar包:

<!--EasyPoi导入导出-->
<dependency>
    <groupId>cn.afterturn</groupId>
    <artifactId>easypoi-base</artifactId>
    <version>3.0.3</version>
    <exclusions>
        <exclusion>
            <artifactId>guava</artifactId>
            <groupId>com.google.guava</groupId>
        </exclusion>
    </exclusions>
</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>

封装实体类信息:

UserExcel:

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

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

/**
 * @author gourd
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
@ExcelTarget("userExcel")
public class UserExcel implements Serializable {

    /**
     * 名称
     */
    @Excel(name = "姓名",orderNum = "1")
    private String name;
    /**
     * 年龄
     */
    @Excel(name = "年龄",orderNum = "2",groupName = "基本信息")
    private Integer age;

    /**
     * 性别
     */
    @Excel(name = "性别",orderNum = "2",replace = {"男_M", "女_F","未知_X"},groupName = "基本信息")
    private String sex;


    /**
     * 手机
     */
    @Excel(name = "手机",orderNum = "3",width = 20,groupName = "联系方式")
    private String mobilePhone;

    /**
     * 邮箱
     */
    @Excel(name = "邮箱",orderNum = "4",width = 20,groupName = "联系方式", isWrap=true)
    private String email;

    /**
     * 昵称
     */
    @Excel(name = "昵称",orderNum = "5",groupName = "其他信息")
    private String nickName;

    @Excel(name = "生日", exportFormat = "yyyy-MM-dd", orderNum = "6",groupName = "其他信息")
    private Date birth;
}

 DeptExcel:

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

import java.io.Serializable;
import java.util.List;

/**
 * @author gourd
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
@ExcelTarget("deptExcel")
public class DeptExcel implements Serializable {

    /**
     * 部门代码
     */
    @Excel(name = "部门代码", orderNum = "2", width = 20, needMerge = true)
    private String code;
    /**
     * 部门名称
     */
    @Excel(name = "部门名称", orderNum = "1", width = 20, needMerge = true)
    private String name;

    @ExcelCollection(name = "员工信息", orderNum = "3")
    private List<UserExcel> users;


}

excel导入导出工具类:

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 lombok.extern.slf4j.Slf4j;
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;

/**
 * @author gourd
 */
@Slf4j
public class ExcelUtil {


    public static boolean isExcel2003(String filePath)
    {
        return filePath.matches("^.+\\.(?i)(xls)$");
    }

    public static boolean isExcel2007(String filePath)
    {
        return filePath.matches("^.+\\.(?i)(xlsx)$");
    }


    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);
        }

    }

    public static void downLoadExcel(String fileName, HttpServletResponse response, Workbook workbook) {
        try {
            // 告诉浏览器用什么软件可以打开此文件
            response.setHeader("content-Type", "application/vnd.ms-excel");
            //设置浏览器响应头对应的Content-disposition
            response.setHeader("Content-Disposition",
                    "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            //编码
            response.setCharacterEncoding("UTF-8");
            workbook.write(response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                workbook.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    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){
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        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){
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

}

多sheet导出demo:

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import com.gourd.base.utils.DateUtil;
import com.gourd.base.utils.ExcelUtil;
import com.gourd.web.excel.entity.DeptExcel;
import com.gourd.web.excel.entity.UserExcel;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author gourd
 */
@Service
public class ExcelService {

    /**
     * 多sheet导出示例
     *
     * @return
     */
    public void exportSheets(HttpServletResponse response) {
        // 准备测试数据
        List<UserExcel> userExcels = new ArrayList<>();
        UserExcel userExcel = new UserExcel();
        userExcel.setName("gourd");
        userExcel.setAge(23);
        userExcel.setSex("M");
        userExcel.setMobilePhone("10086");
        userExcel.setEmail("163.com");
        userExcel.setNickName("gourd");
        userExcel.setBirth(new Date());
        userExcels.add(userExcel);
        UserExcel userExcel2 = new UserExcel();
        userExcel2.setName("葫芦");
        userExcel2.setAge(23);
        userExcel2.setSex("X");
        userExcel2.setMobilePhone("110");
        userExcel2.setEmail("aaa@qq.com");
        userExcel2.setNickName("gourd");
        userExcel2.setBirth(new Date());
        userExcels.add(userExcel2);
        List<DeptExcel> deptExcels = new ArrayList<>();
        DeptExcel deptExcel = new DeptExcel();
        deptExcel.setCode("T-01");
        deptExcel.setName("技术一部");
        deptExcel.setUsers(userExcels);
        deptExcels.add(deptExcel);
        DeptExcel deptExcel2 = new DeptExcel();
        deptExcel2.setCode("T-02");
        deptExcel2.setName("技术二部");
        deptExcel2.setUsers(userExcels);
        deptExcels.add(deptExcel2);

        // 创建参数对象
        ExportParams exportParams1 = new ExportParams();
        // 设置sheet得名称
        exportParams1.setSheetName("部门人员信息");
        ExportParams exportParams2 = new ExportParams();
        exportParams2.setSheetName("用户信息");

        // 创建sheet1使用得map
        Map<String, Object> deptDataMap = new HashMap<>(4);
        // title的参数为ExportParams类型
        deptDataMap.put("title", exportParams1);
        // 模版导出对应得实体类型
        deptDataMap.put("entity", DeptExcel.class);
        // sheet中要填充得数据
        deptDataMap.put("data", deptExcels);

        // 创建sheet2使用得map
        Map<String, Object> userDataMap = new HashMap<>(4);
        userDataMap.put("title", exportParams2);
        userDataMap.put("entity", UserExcel.class);
        userDataMap.put("data", userExcels);
        // 将sheet1和sheet2使用得map进行包装
        List<Map<String, Object>> sheetsList = new ArrayList<>();
        sheetsList.add(deptDataMap);
        sheetsList.add(userDataMap);
        // 执行方法
        Workbook workbook = ExcelExportUtil.exportExcel(sheetsList, ExcelType.HSSF);
        ExcelUtil.downLoadExcel("用户信息"+ DateUtil.date2Str(new Date(),"YYYY-MM-dd-HH-mm") +".xls",response,workbook);
    }

}

Controller掉用:

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.gourd.base.utils.CollectionCopyUtil;
import com.gourd.base.utils.DateUtil;
import com.gourd.base.utils.ExcelUtil;
import com.gourd.web.excel.entity.UserExcel;
import com.gourd.web.excel.service.ExcelService;
import com.gourd.web.rbac.entity.RbacUser;
import com.gourd.web.rbac.service.RbacUserService;
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.util.Date;
import java.util.List;

/**
 * @author gourd
 */
@RestController
@RequestMapping("/excel")
@Api(tags = "excel", description = "excel控制器")
public class ExcelController {

    @Autowired
    private RbacUserService userService;

    @Autowired
    private ExcelService excelService;

    @GetMapping("/export")
    @ApiOperation(value="导出")
    public void export(HttpServletResponse response) {
        // 模拟从数据库获取需要导出的数据
        List<RbacUser> personList = userService.findAll();
        List<UserExcel> userExcelList =  CollectionCopyUtil.copyList(personList,UserExcel.class);
        //导出操作
        ExcelUtil.exportExcel(userExcelList,"用户列表","用户", UserExcel.class,"用户信息"+ DateUtil.date2Str(new Date(),"YYYY-MM-dd-HH-mm") +".xls",response);

    }

    @GetMapping("/export-sheets")
    @ApiOperation(value="导出多个sheet")
    public void exportSheets(HttpServletResponse response) {
        excelService.exportSheets(response);
    }

    @PostMapping("/import")
    @ApiOperation(value="导入")
    public void importExcel(@RequestParam("file") MultipartFile file) {
        ImportParams importParams = new ImportParams();
        // 数据处理
        importParams.setHeadRows(1);
        importParams.setTitleRows(1);

        // 需要验证
        importParams.setNeedVerfiy(true);

        try {
            ExcelImportResult<RbacUser> result = ExcelImportUtil.importExcelMore(file.getInputStream(), RbacUser.class,
                    importParams);

            List<RbacUser> successList = result.getList();
            for (RbacUser demoExcel : successList) {
              System.out.println(demoExcel);
            }
        } catch (IOException e) {
        } catch (Exception e) {
        }
    }
}

调用export-sheets接口导出结果截图:

【easypoi】 实现excel导入导出(多sheet)

【easypoi】 实现excel导入导出(多sheet)

 如果你使用的POI请参考:https://blog.csdn.net/HXNLYW/article/details/96830248 

@Excel注解属性解释:

属性 类型 类型 说明
name String null 列名
needMerge boolean fasle 纵向合并单元格
orderNum String "0" 列的排序,支持name_id
replace String[] {} 值得替换 导出是{a_id,b_id} 导入反过来
savePath String "upload" 导入文件保存路径
type int 1 导出类型 1 是文本 2 是图片,3 是函数,10 是数字 默认是文本
width double 10 列宽
height double 10 列高,后期打算统一使用@ExcelTarget的height,这个会被废弃,注意
isStatistics boolean fasle 自动统计数据,在追加一行统计,把所有数据都和输出这个处理会吞没异常,请注意这一点
isHyperlink boolean false 超链接,如果是需要实现接口返回对象
isImportField boolean true 校验字段,看看这个字段是不是导入的Excel中有,如果没有说明是错误的Excel,读取失败,支持name_id
exportFormat String "" 导出的时间格式,以这个是否为空来判断是否需要格式化日期
importFormat String "" 导入的时间格式,以这个是否为空来判断是否需要格式化日期
format String "" 时间格式,相当于同时设置了exportFormat 和 importFormat
databaseFormat String "yyyyMMddHHmmss" 导出时间设置,如果字段是Date类型则不需要设置 数据库如果是string 类型,这个需要设置这个数据库格式,用以转换时间格式输出
numFormat String "" 数字格式化,参数是Pattern,使用的对象是DecimalFormat
imageType int 1 导出类型 1 从file读取 2 是从数据库中读取 默认是文件 同样导入也是一样的
suffix String "" 文字后缀,如% 90 变成90%
isWrap boolean true 是否换行 即支持\n
mergeRely int[] {} 合并单元格依赖关系,比如第二列合并是基于第一列 则{1}就可以了
mergeVertical boolean fasle 纵向合并内容相同的单元格