1. 程式人生 > 其它 >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();
        }
    }
    
  • 測試