springboot集成easyPoi实现excel数据导入到Mysql数据库

时间:2021-08-12
本文章向大家介绍springboot集成easyPoi实现excel数据导入到Mysql数据库,主要包括springboot集成easyPoi实现excel数据导入到Mysql数据库使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

springboot集成easyPoi实现excel数据导入到Mysql数据库

  • easyPoi官方文档:http://easypoi.mydoc.io/

  • 通过Mybatis generator生成相关Tbxxx,TbxxxExample,TbxxxMapper.java,TbxxxMapper.xml,TbxxxService

  • 引入依赖:

    		<dependency>
                <groupId>cn.afterturn</groupId>
                <artifactId>easypoi-base</artifactId>
                <version>3.2.0</version>
            </dependency>
            <dependency>
                <groupId>cn.afterturn</groupId>
                <artifactId>easypoi-web</artifactId>
                <version>3.2.0</version>
            </dependency>
            <dependency>
                <groupId>cn.afterturn</groupId>
                <artifactId>easypoi-annotation</artifactId>
                <version>3.2.0</version>
            </dependency>
    
  • 注解实体类:

    import cn.afterturn.easypoi.excel.annotation.Excel;
    import com.yun.cloud.base.model.BaseModel;
    import lombok.Data;
    
    import java.io.Serializable;
    
    @Data
    public class TbProductStandard extends BaseModel implements Serializable {
        private String id;
    
        @Excel(name = "code")
        private String code;
    
        @Excel(name = "parent_code")
        private String parentId;
    
        @Excel(name = "type_name")
        private String typeName;
    }
    

    相关注解介绍:

    @Excel 作用到实体类字段上面,是对Excel一列的一个描述

    @ExcelCollection 表示一个集合,主要针对一对多的导出,比如一个老师对应多个科目,科目就可以用集合表示

    @ExcelEntity 表示一个继续深入导出的实体,但他没有太多的实际意义,只是告诉系统这个对象里面同样有导出的字段

    @ExcelIgnore 和名字一样表示这个字段被忽略跳过这个导导出

    @ExcelTarget 这个是作用于最外层的对象,描述这个对象的id,以便支持一个对象可以针对不同导出做出不同处理
    ————————————————
    原文链接:https://blog.csdn.net/weixin_41922289/article/details/100191112

    • 受注解的excel格式:
  • 设置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 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;
    
    public class ProductExcelUtils {
        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) {
                // 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;
        }
    }
    
    
  • controller层:

    import com.yun.cloud.base.result.Result;
    import com.yun.cloud.gap.business.ProductStandardBusiness;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.PostMapping;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestParam;
    import org.springframework.web.bind.annotation.RestController;
    import org.springframework.web.multipart.MultipartFile;
    
    @RestController
    @RequestMapping("/productstandard")
    public class ProductStandardController {
        @Autowired
        private ProductStandardBusiness productStandardBusiness;
        /**
         * 导入excel
         * @param file
         * @return
         */
        @PostMapping("/importExcel")
        public Result importExcel(@RequestParam("file") MultipartFile file) {
            return productStandardBusiness.importExcel(file);
        }
    }
    
  • business层:

    import cn.afterturn.easypoi.excel.ExcelImportUtil;
    import cn.afterturn.easypoi.excel.entity.ImportParams;
    import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
    import com.alibaba.fastjson.JSONObject;
    import com.yun.cloud.base.result.Result;
    import com.yun.cloud.base.utils.IdGenUtil;
    import com.yun.cloud.gap.model.TbProductStandard;
    import com.yun.cloud.gap.model.TbProductStandardExample;
    import com.yun.cloud.gap.service.TbProductStandardService;
    import lombok.extern.slf4j.Slf4j;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.stereotype.Service;
    import org.springframework.web.multipart.MultipartFile;
    
    import java.util.List;
    
    @Slf4j
    @Service("ProductStandardBusiness")
    public class ProductStandardBusiness {
        @Autowired
        private TbProductStandardService tbProductStandardService;
    
        @Value("${machine}")
        private int machineId;
    
        @Value("${datacenter}")
        private int dataCenterId;
    
        public Result importExcel(MultipartFile file) {
            ImportParams importParams = new ImportParams();
            // 数据处理
            importParams.setHeadRows(1);
            importParams.setTitleRows(1);
            // 需要验证
            importParams.setNeedVerfiy(false);
            try {
                ExcelImportResult<TbProductStandard> result = ExcelImportUtil.importExcelMore(file.getInputStream(), TbProductStandard.class,
                        importParams);
                List<TbProductStandard> tbProductStandardList = result.getList();
                for (TbProductStandard tbProductStandard : tbProductStandardList) {
                    log.info("从Excel导入数据到数据库的详细为 :{}", JSONObject.toJSONString(tbProductStandard));
                    //保存到mysql
                    String id = IdGenUtil.getNextId(machineId,dataCenterId);
                    tbProductStandard.setId(id);
                    int i = tbProductStandardService.insertSelective(tbProductStandard);
                    if(i < 1){
                        log.error("保存失败");
                        return Result.err("保存失败");
                    }
                }
                log.info("从Excel导入数据一共 {} 行 ", tbProductStandardList.size());
            } catch (Exception e) {
                log.error("导入失败:{}", e.getMessage());
                return Result.err("导入失败");
            }
            return Result.suc();
        }
    }
    
  • 测试

原文地址:https://www.cnblogs.com/horseweed/p/15134814.html