EasyPoi导入与导出

1.导入依赖


    cn.afterturn
    easypoi-spring-boot-starter
    4.2.0

2.工具类

package com.geidco.dcp.util;

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 cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
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.InputStream;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;

/**
 * @author XuPengFei
 */
public class ExcelUtils {
    /**
     * excel 导出
     *
     * @param list           数据
     * @param title          标题
     * @param sheetName      sheet名称
     * @param pojoClass      pojo类型
     * @param fileName       文件名称
     * @param isCreateHeader 是否创建表头
     * @param response
     */
    public static void exportExcel(List list, String title, String sheetName, Class pojoClass, String fileName, boolean isCreateHeader, HttpServletResponse response) throws IOException {
        ExportParams exportParams = new ExportParams(title, sheetName, ExcelType.XSSF);
        exportParams.setCreateHeadRows(isCreateHeader);
        defaultExport(list, pojoClass, fileName, response, exportParams);
    }

    /**
     * excel 导出
     *
     * @param list      数据
     * @param title     标题
     * @param sheetName sheet名称
     * @param pojoClass pojo类型
     * @param fileName  文件名称
     * @param response
     */
    public static void exportExcel(List list, String title, String sheetName, Class pojoClass, String fileName, HttpServletResponse response) throws IOException {
        ExportParams params = new ExportParams(title, sheetName, ExcelType.XSSF);

        defaultExport(list, pojoClass, fileName, response, params);
    }

    /**
     * excel 导出
     *
     * @param list         数据
     * @param pojoClass    pojo类型
     * @param fileName     文件名称
     * @param response
     * @param exportParams 导出参数
     */
    public static void exportExcel(List list, Class pojoClass, String fileName, ExportParams exportParams, HttpServletResponse response) throws IOException {
        defaultExport(list, pojoClass, fileName, response, exportParams);
    }

    /**
     * excel 导出
     *
     * @param list     数据
     * @param fileName 文件名称
     * @param response
     */
    public static void exportExcel(List> list, String fileName, HttpServletResponse response) throws IOException {
        defaultExport(list, fileName, response);
    }

    /**
     * 默认的 excel 导出
     *
     * @param list         数据
     * @param pojoClass    pojo类型
     * @param fileName     文件名称
     * @param response
     * @param exportParams 导出参数
     */
    private static void defaultExport(List list, Class pojoClass, String fileName, HttpServletResponse response, ExportParams exportParams) throws IOException {
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, pojoClass, list);
        downLoadExcel(fileName, response, workbook);
    }

    /**
     * 默认的 excel 导出
     *
     * @param list     数据
     * @param fileName 文件名称
     * @param response
     */
    private static void defaultExport(List> list, String fileName, HttpServletResponse response) throws IOException {
        Workbook workbook = ExcelExportUtil.exportExcel(list, ExcelType.HSSF);
        downLoadExcel(fileName, response, workbook);
    }

    /**
     * 下载
     *
     * @param fileName 文件名称
     * @param response
     * @param workbook excel数据
     */
    private static void downLoadExcel(String fileName, HttpServletResponse response, Workbook workbook) throws IOException {
        try {
            response.setCharacterEncoding("UTF-8");
            response.setHeader("content-Type", "application/vnd.ms-excel");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName + "." + ExcelTypeEnum.XLSX.getValue(), "UTF-8"));
            workbook.write(response.getOutputStream());
        } catch (Exception e) {
            throw new IOException(e.getMessage());
        }
    }

    /**
     * excel 导入
     *
     * @param filePath   excel文件路径
     * @param titleRows  标题行
     * @param headerRows 表头行
     * @param pojoClass  pojo类型
     * @param 
     * @return
     */
    public static  List importExcel(String filePath, Integer titleRows, Integer headerRows, Class pojoClass) throws IOException {
        if (StringUtils.isBlank(filePath)) {
            return null;
        }
        ImportParams params = new ImportParams();
        params.setTitleRows(titleRows);
        params.setHeadRows(headerRows);
        params.setNeedSave(true);
        params.setSaveUrl("/excel/");
        try {
            return ExcelImportUtil.importExcel(new File(filePath), pojoClass, params);
        } catch (NoSuchElementException e) {
            throw new IOException("模板不能为空");
        } catch (Exception e) {
            throw new IOException(e.getMessage());
        }
    }

    /**
     * excel 导入
     *
     * @param file      excel文件
     * @param pojoClass pojo类型
     * @param 
     * @return
     */
    public static  List importExcel(MultipartFile file, Class pojoClass) throws IOException {
        return importExcel(file, 1, 1, pojoClass);
    }

    /**
     * excel 导入
     *
     * @param file       excel文件
     * @param titleRows  标题行
     * @param headerRows 表头行
     * @param pojoClass  pojo类型
     * @param 
     * @return
     */
    public static  List importExcel(MultipartFile file, Integer titleRows, Integer headerRows, Class pojoClass) throws IOException {
        return importExcel(file, titleRows, headerRows, false, pojoClass);
    }

    /**
     * excel 导入
     *
     * @param file       上传的文件
     * @param titleRows  标题行
     * @param headerRows 表头行
     * @param needVerfiy 是否检验excel内容
     * @param pojoClass  pojo类型
     * @param 
     * @return
     */
    public static  List importExcel(MultipartFile file, Integer titleRows, Integer headerRows, boolean needVerfiy, Class pojoClass) throws IOException {
        if (file == null) {
            return null;
        }
        try {
            return importExcel(file.getInputStream(), titleRows, headerRows, needVerfiy, pojoClass);
        } catch (Exception e) {
            throw new IOException(e.getMessage());
        }
    }

    /**
     * excel 导入
     *
     * @param inputStream 文件输入流
     * @param titleRows   标题行
     * @param headerRows  表头行
     * @param needVerfiy  是否检验excel内容
     * @param pojoClass   pojo类型
     * @param 
     * @return
     */
    public static  List importExcel(InputStream inputStream, Integer titleRows, Integer headerRows, boolean needVerfiy, Class pojoClass) throws IOException {
        if (inputStream == null) {
            return null;
        }
        ImportParams params = new ImportParams();
        params.setTitleRows(titleRows);
        params.setHeadRows(headerRows);
        params.setSaveUrl("/excel/");
        params.setNeedSave(true);
        try {
            return ExcelImportUtil.importExcel(inputStream, pojoClass, params);
        } catch (NoSuchElementException e) {
            throw new IOException("excel文件不能为空");
        } catch (Exception e) {
            throw new IOException(e.getMessage());
        }
    }

    public static  List importExcel111(InputStream inputStream, Integer titleRows, Integer headerRows, boolean needVerfiy, Class pojoClass) throws IOException {
        if (inputStream == null) {
            return null;
        }
        ImportParams params = new ImportParams();
        params.setTitleRows(titleRows);
        params.setHeadRows(headerRows);
        params.setSaveUrl("/excel/");
        params.setNeedSave(true);
        try {
            return ExcelImportUtil.importExcel(inputStream, pojoClass, params);
        } catch (NoSuchElementException e) {
            throw new IOException("excel文件不能为空");
        } catch (Exception e) {
            throw new IOException(e.getMessage());
        }
    }

    /**
     * Excel 类型枚举
     */
    enum ExcelTypeEnum {
        /**
         * XLS格式
         */
        XLS("xls"), XLSX("xlsx");
        private String value;

        ExcelTypeEnum(String value) {
            this.value = value;
        }

        public String getValue() {
            return value;
        }

        public void setValue(String value) {
            this.value = value;
        }
    }

    public static  void downLoadVolFailExcel(ExcelImportResult result, HttpServletResponse response, Class pojoClass) throws IOException {
        /**
         * 验证失败的就返回给前端用户,并且带有错误消息提示内容,文件下载功能:将验证失败的数据放入excel文件中,让用户下载
         */
        if (result.isVerifyFail()) {
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setHeader("Content-disposition", "attachment;filename=errors.xlsx");
            response.setHeader("Pragma", "No-cache");
            ServletOutputStream fos = null;
            try {
                fos = response.getOutputStream();
                /**
                 * 直接获取验证失败的那个Workbook对象
                 */
                result.getFailWorkbook().write(fos);
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

3.实体类

public class EmailTaskDetail implements Serializable {
    /** 语言版本(zh,en) */
	@Excel(name = "语言版本", width = 15, addressList = true, replace = {"中文_zh", "英文_en"})
	private String languageType; // 必须
	/** 收件人名称 */
	@Excel(name = "收件人名称", width = 20)
	private String recieveName; // 必须
	/** 收件人邮箱 */
    // 需要加入此注解
	@Excel(name = "收件人邮箱", width = 20)
	private String recieveEmail; // 非必须
	/** 邮件内容 */
	private String emailContent; // 非必须
}

4.导出功能

@GetMapping("/downloadTemplate")
@Log("下载模板")
public Result downloadTemplate(HttpServletResponse response) {
    try {
        // 组装数据
        List list = new ArrayList();
        ExcelUtils.exportExcel(list, "批量发送邮件信息", "批量发送邮件信息", EmailTaskDetail.class, "批量发送邮件信息", response);
        return Result.ok("下载成功!");
    } catch (Exception e) {
          return Result.error("下载失败!");
    }
}

5.普通导入功能

    @PostMapping(value = "/importVolunteerData")
    @ResponseBody
    @Log("志愿者导入")
    public Result importVolunteerData(@RequestParam("meetingId") String meetingId, @RequestParam("file") MultipartFile file, HttpServletResponse response) {
        if (StringUtils.isEmpty(meetingId)) {
            return Result.error("会议id不能为空");
        }
        Map allOfficeMap = SysUtils.getDictMap("VOL_LANGUAGE_DICT");
        HashMap officeMap = new HashMap<>();
        for (String key : allOfficeMap.keySet()) {
            officeMap.put(allOfficeMap.get(key), key);
        }

        String officeKey = null;
        List list = null;
        List failList = null;
        ExcelImportResult result = null;

        try {
            ImportParams importParams = new ImportParams();
            importParams.setTitleRows(1);
            importParams.setHeadRows(1);
            result = ExcelImportUtil.importExcelMore(file.getInputStream(), MeetingVolunteer.class, importParams);
            list = result.getList();
            failList = result.getFailList();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (CollectionUtils.isNullOrEmpty(list)) {
            return Result.error("没有有效的数据,导入数据失败");
        }

        StringBuilder stringBuilder = new StringBuilder();
        String userId = SysUtils.getActiveUser().getUserId().toString();
        list.forEach(meetingVolunteer -> {
            // 处理自己的业务逻辑
            meetingVolunteer.setVolunteerStatus("02");
            meetingVolunteer.setMeetingId(meetingId);
            meetingVolunteer.setId(idWorker.nextId() + "");
            meetingVolunteer.setUpdateBy(userId);
            meetingVolunteer.setCreateBy(userId);

            // 导入去重
            // 导入志愿者手机号
            String volunteerMobile = meetingVolunteer.getVolunteerMobile();
            List volunteerList = meetingVolunteerService.findVolunteerMobile(volunteerMobile);
            if (volunteerList.size() == 0 && StringUtils.isNotBlank(volunteerMobile)) {
                meetingVolunteerService.add(meetingVolunteer);
            }

            if (StringUtils.isBlank(volunteerMobile) || volunteerList.size() != 0) {
                stringBuilder.append(meetingVolunteer.getVolunteerName() + ",");
            }
        });

        try {
            ExcelUtils.downLoadVolFailExcel(result, response, MeetingVolunteer.class);
        } catch (IOException e) {
            e.printStackTrace();
        }
        int length = stringBuilder.length();
        return Result.ok(length == 0 ? "导入成功!" : "导入成功!导入志愿者手机号为空的有:" + stringBuilder + ",已跳过");
}

5.excel模板自定义列导入功能

示例图解:

EasyPoi导入与导出_第1张图片

EasyPoi导入与导出_第2张图片

    @PostMapping(value = "/importEmailTaskDetailData")
    @ResponseBody
    @Log("导入邮件信息")
    public Result importEmailTaskDetailData(HttpServletRequest request, @RequestParam("file") MultipartFile file, HttpServletResponse response) {
        String taskId = request.getParameter("taskId");
        if (StringUtils.isEmpty(taskId)) {
            return Result.error("任务id不能为空");
        }

        String officeKey = null;

        List list = null;
        List failList = null;
        ExcelImportResult result = null;
        ArrayList headerList = null;

        List> mapList = null;
        try {
            ImportParams params = new ImportParams();
            params.setHeadRows(1);
            params.setTitleRows(1);
            mapList = ExcelImportUtil.importExcel(file.getInputStream(), Map.class, params);
            System.out.println(mapList);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (CollectionUtils.isNullOrEmpty(mapList)) {
            return Result.error("没有有效的数据,导入数据失败");
        }

        String userId = SysUtils.getActiveUser().getUserId().toString();
        mapList.forEach(map -> {
            // 创建实体类对象
            EmailTaskDetail detail = new EmailTaskDetail();

            String recieveName = "";
            String recieveEmail = "";
            String content = "";
            // 获取key
            Set keySet = map.keySet();
            System.out.println(keySet);
            //邮件内容参数集合
            Map parameterMap = new HashMap(100, 100);
            for (String str : keySet) {
                String value = map.get(str).toString();
                if (StringUtils.isNotBlank(value)) {
                    parameterMap.put("{" + str + "}", value);
                }
            }
            // 获取值
            recieveName = (String) map.get("收件人名称");
            recieveEmail = (String) map.get("收件人邮箱");

            DateTimeFormatter ymdEn = DateTimeFormatter.ofPattern("dd MMM uuuu", Locale.ENGLISH);
            String dateEn = LocalDate.now().format(ymdEn);
            // 替换模板变量,模板变量示例:{xxxx}
            parameterMap.put("{中文日期}", LocalDate.now().toString());
            parameterMap.put("{英文日期}", dateEn);
            // 我这里区分中英文,中文:zh,英文:en
            String language = (String) map.get("语言版本");
            EmailTaskTemplate template = emailTaskTemplateService.getObjectByKey(taskId);
            if ("中文".equals(language)) {
                String contentZh = template.getEmailContentZh();
                // 替换之后的内容
                content = SysTemplateUtil.getEmailTemplateContent(contentZh, parameterMap);
                detail.setLanguageType("zh");// 中文
            } else {
                String contentEn = template.getEmailContentEn();
                // 替换之后的内容
                content = SysTemplateUtil.getEmailTemplateContent(contentEn, parameterMap);
                detail.setLanguageType("en");// 英文
            }

            detail.setTemplateId(taskId);
            detail.setId(idWorker.nextId() + "");
            detail.setIsSend("N");
            detail.setCreateBy(userId);
            detail.setUpdateBy(userId);
            detail.setRecieveEmail(recieveEmail);
            detail.setRecieveName(recieveName);
            detail.setEmailContent(content);
            // 保存导入的数据
            emailTaskDetailService.add(detail);
        });
        return Result.ok("导入成功!");
    }

 

你可能感兴趣的:(Java,java,poi,excel,导入导出)