枚举中文转数字并easyexcel导入(读取Read)数据至数据库,用监听器解决导入关联多表的问题
以下內容皆為本人學習過程中的所學的知識,全根據自己所學思路來寫的。
大致流程如下:
一、創建實體類,注意有一個是導入的模板實體模型類(CustomManageAndCustomerInformationReadVO),有一個是這個模塊的主表實體(CustomManage),模塊主表實體才會連接到數據庫的數據,而模板實體模型類是導入所要求有的字段,并且哪個字段在哪一列從0開始。
二、在controller層調用ExcelUtils工具類下的customerInformationReadExcel()方法。
三、進入ExcelUtils工具類編寫customerInformationReadExcel()方法,其中需要調用到CustomManageListener()監聽器也可稱之為解析器。
四、導入的難點就在于監聽器的編寫,如若導入的數據屬于一張表還不難,重點是我這次做的是多表的,需要進行連表操作,調用其他表的mapper和service。不會做就覺得難。做了覺得也還行不是特別難,就像地上本沒有路走的人多了也就成了路。監聽器中調用了公共枚舉中文轉數字的方法。
五、進入公共枚舉類,編寫中文轉數字的getEnumNum()方法,實現中文獲取數字,導入,(從excel中導入數據至數據庫)。
1.創建實體類,注意有一個是導入的模板實體模型類(CustomManageAndCustomerInformationReadVO),有一個是這個模塊的主表實體(CustomManage),模塊主表實體才會連接到數據庫的數據,而模板實體模型類是導入所要求有的字段,并且哪個字段在哪一列從0開始。
package com.theiavis.workcloud.project.sale.bean;import java.io.Serializable; import java.util.Date;import com.alibaba.excel.annotation.ExcelIgnore; import com.alibaba.excel.annotation.ExcelProperty; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableId; import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.theiavis.workcloud.common.entity.BaseEntity; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.*; import lombok.experimental.Accessors; import org.springframework.web.bind.annotation.ModelAttribute;/*** custom_manage :*/ @Data @Accessors(chain=true) @AllArgsConstructor @NoArgsConstructor @ApiModel("客戶管理對象") public class CustomManage extends BaseEntity implements Serializable {private static final long serialVersionUID = 1L;/*** 主鍵 : id,*/@ExcelIgnore@TableId(value = "id", type = IdType.AUTO)private Integer id;/*** sale_time, 銷售時間,kpi關聯,需拆分-年*/@ExcelIgnore@ExcelProperty(value = {"年份"}, index = 0)@ApiModelProperty(value = "銷售時間-年", required = true)private String saleTimeYear;/*** sale_time, 銷售時間,kpi關聯,需拆分-月*/@ExcelIgnore@ExcelProperty(value = {"所屬月份"}, index = 1)@ApiModelProperty(value = "銷售時間-月", required = true)private String saleTimeMonth;/*** proj_num, project-》projo_num,創建時間與項目表關聯*/@ExcelIgnore@ExcelProperty(value = {"創建時間與項目表關聯"}, index = 2)@ApiModelProperty(value = "創建時間與項目表關聯", required = true)private String projNum;/*** follow_id, 跟進人標識user->user_id*/@ExcelIgnore@ExcelProperty(value = {"跟進人標識user->user_id"}, index = 3)@ApiModelProperty(value = "跟進人標識user->user_id", required = true)private String followId;/*** create_id, 創建人標識user->user_id*/@ExcelIgnore@ExcelProperty(value = {"創建人標識user->user_id"}, index = 4)@ApiModelProperty(value = "創建人標識user->user_id", required = true)private String createId;/*** company, 對接公司名稱*/@ExcelIgnore@ExcelProperty(value = {"公司名稱"}, index = 5)@ApiModelProperty(value = "對接公司名稱", required = true)private String company;/*** custom_type, 客戶類型(0、商業公司1、政府2、地產商3、規劃院)*/@ExcelIgnore@ExcelProperty(value = {"客戶類型(0、商業公司1、政府2、地產商3、規劃院)"}, index = 6)@ApiModelProperty(value = "客戶類型(0、商業公司1、政府2、地產商3、規劃院)", required = true)private String customType;/*** city, 客戶所在城市*/@ExcelIgnore@ExcelProperty(value = {"客戶所在城市"}, index = 7)@ApiModelProperty(value = "客戶所在城市", required = true)private String city;/*** custom_department, 客戶所在部門*/@ExcelIgnore@ExcelProperty(value = {"客戶所在部門"}, index = 8)@ApiModelProperty(value = "客戶所在部門", required = true)private String customDepartment;/*** contact, 聯系人名字(全稱)*/@ExcelIgnore@ExcelProperty(value = {"聯系人名字(全稱)"}, index = 9)@ApiModelProperty(value = "聯系人名字(全稱)", required = true)private String contact;/*** mobile, 聯系人電話*/@ExcelIgnore@ExcelProperty(value = {"聯系人電話"}, index = 10)@ApiModelProperty(value = "聯系人電話", required = true)private String mobile;/*** email, 聯系人郵箱*/@ExcelIgnore@ExcelProperty(value = {"聯系人郵箱"}, index = 11)@ApiModelProperty(value = "聯系人郵箱", required = true)private String email;/*** custom_source, 新舊客戶類型(0.移交客戶1.新客戶)*/@ExcelIgnore@ExcelProperty(value = {"新舊客戶類型(0.移交客戶1.新客戶)"}, index = 12)@ApiModelProperty(value = "新舊客戶類型(0.移交客戶1.新客戶)", required = true)private String customSource;/*** custom_id, 客戶id*/@ExcelIgnore@ExcelProperty(value = {"客戶id"}, index = 13)@ApiModelProperty(value = "客戶id", required = false)private String customId;/*** permit_code, 權限碼*/@ExcelIgnore@ExcelProperty(value = {"權限碼"}, index = 14)@ApiModelProperty(value = "權限碼", required = true)private String permitCode;/*** dept_id, 部門id*/@ExcelIgnore// @ExcelProperty(value = {"部門id"}, index = 15)@ApiModelProperty(value = "部門id", required = true)private Integer deptId;/*** agreement_id, proj_agreement->id合同標識*/@ExcelIgnore// @ExcelProperty(value = {"id合同標識"}, index = 16)@ApiModelProperty(value = "id合同標識", required = false)private Integer agreementId;/*** creat_Time, create_Time創建時間*/@ExcelIgnore@ExcelProperty(value = {"create_Time創建時間"}, index = 17)@ApiModelProperty(value = "create_Time創建時間", required = false)@JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8")private Date createTime;/*** is_delete, 是否刪除*/@ExcelIgnore@ExcelProperty(value = {"是否刪除0.否1.是"}, index = 18)@ApiModelProperty(value = "是否刪除0.否1.是", required = true)private String isDelete;} package com.theiavis.workcloud.project.sale.vo;import com.alibaba.excel.annotation.ExcelIgnore; import com.alibaba.excel.annotation.ExcelProperty; import com.baomidou.mybatisplus.annotation.TableField; import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonIgnore; import io.swagger.annotations.ApiModelProperty; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import lombok.experimental.Accessors;import java.util.Date;/*** 根據"客戶信息導入模板"批量導入* @author xql*/ @Data //@Accessors(chain=true) @AllArgsConstructor @NoArgsConstructor public class CustomManageAndCustomerInformationReadVO {/*** stage, 商機尋找(0.商機線索,1.在談項目 2.簽約項目 3.已歸檔項目4.前期介入5.項目報價6.關鍵人物接觸7.方案匯報8.方案階段9.投標階段10.合同階段11.項目暫停)*/@ApiModelProperty(value = "商機尋找(0.商機線索,1.在談項目 2.簽約項目 3.已歸檔項目4.前期介入5.項目報價6.關鍵人物接觸7.方案匯報8.方案階段9.投標階段10.合同階段11.項目暫停)", required = true)@ExcelProperty(value = "所屬階段", index = 0)private String stage;/*** sale_time, 銷售時間,kpi關聯,需拆分-年*/@ExcelProperty(value = "年份", index = 1)private String saleTimeYear;/*** sale_time, 銷售時間,kpi關聯,需拆分-月*/@ExcelProperty(value = "所屬月份", index = 2)private String saleTimeMonth;/*** 客戶來源*/@ExcelProperty(value = "客戶來源", index = 3)@TableField(exist = false)@ApiModelProperty(value = "客戶來源", required = true)private String source;/*** company, 對接公司名稱*/@ExcelProperty(value = "公司名稱", index = 4)private String company;/*** 項目名 項目名稱*/@ExcelProperty(value = "項目名稱", index = 5)private String projName;/*** 項目地址*/@ExcelProperty(value = "項目地址", index = 6)@TableField(exist = false)@ApiModelProperty(value = "項目地址", required = true)private String address;/*** 項目類型*/@ExcelProperty(value = "項目類型", index = 7)@TableField(exist = false)@ApiModelProperty(value = "項目類型(項目類型(0、數字大屏1、數字沙盤2、數字展項3、數字展廳4、CIM 5、VRXR 6:其他)", required = true)private String projectType;/*** custom_type, 客戶類型(0、商業公司1、政府2、地產商3、規劃院)*/@ExcelProperty(value = "客戶類型", index = 8)@ApiModelProperty(value = "客戶類型(0、商業公司1、政府2、地產商3、規劃院)", required = true)private String customType;/*** city, 客戶所在城市*/@ExcelProperty(value = {"客戶所在城市"}, index = 9)@ApiModelProperty(value = "客戶所在城市", required = true)private String city;/*** custom_department, 客戶所在部門*/@ExcelProperty(value = {"客戶所屬部門"}, index = 10)@ApiModelProperty(value = "客戶所在部門", required = true)private String customDepartment;/*** contact, 聯系人名字(全稱)*/@ExcelProperty(value = "聯系人", index = 11)private String contact;/*** email, 聯系人郵箱*/@ExcelProperty(value = {"聯系人郵箱"}, index = 12)@ApiModelProperty(value = "聯系人郵箱", required = true)private String email;/*** mobile, 聯系人電話*/@ExcelProperty(value = "聯系人電話", index = 13)private String mobile;/*** follow_id, 跟進人名稱*/@ExcelProperty(value = "跟進人", index = 14)private String followName;/*** 跟進結果*/@ExcelProperty(value = "跟進結果", index = 15)@TableField(exist = false)@ApiModelProperty(value = "跟進結果", required = true)private String followResult;/*** 失敗原因*/@ExcelProperty(value = "失敗原因", index = 16)@TableField(exist = false)@ApiModelProperty(value = "失敗原因", required = true)private String followFailResult;/*** 計劃開始時間*/@TableField(exist = false)@ExcelProperty(value = "計劃開始時間(yyyy/mm/dd)", index = 17)@JsonIgnoreprivate Date planStartTime;/*** proj_need, 項目需求*/@TableField(exist = false)@ExcelProperty(value = "項目需求", index = 18)@ApiModelProperty(value = "項目需求", required = true)private String projNeed;/*** 計劃結束時間*/@TableField(exist = false)@ExcelProperty(value = "計劃結束時間(yyyy/mm/dd)", index = 19)@JsonIgnoreprivate Date planEndTime;/*** custom_source, 新舊客戶類型(0.移交客戶1.新客戶)*/@TableField(exist = false)@ExcelProperty(value = "新舊客戶類型", index = 20)private String customSource;/*** product_count, 產品數量*/@TableField(exist = false)@ExcelProperty(value = "產品數量", index = 21)@ApiModelProperty(value = "產品數量", required = true)private String productCount;/*** contract_cash, 預計合同金額*/@TableField(exist = false)@ExcelProperty(value = "預計合同金額(萬元)", index = 22)@ApiModelProperty(value = "預計合同金額", required = true)private String contractCash;/*** place_contract, 是否簽訂合同(0.未簽約1.已簽約)*/@TableField(exist = false)@ExcelProperty(value = "是否簽訂保密協議", index = 23)@ApiModelProperty(value = "是否簽訂保密協議(0.未簽約1.已簽約)", required = true)private String placeContract;/*** effect_pj, 是否當地影響力(0.否1.是)*/@TableField(exist = false)@ExcelProperty(value = "是否當地影響力", index = 24)@ApiModelProperty(value = "是否當地影響力(0.否1.是)", required = true)private String effectPj;/*** 項目進度*/@TableField(exist = false)@ExcelProperty(value = "項目進度",index = 25)@ApiModelProperty(value = "項目進度(0:前期介入1:項目報價2:關鍵人物接觸3:方案制作階段4:方案匯報5:DEMO制作6:投標階段7:簽約階段8:項目站廳)", required = true)private String projProgress;/*** star, 項目星級(數字標識1-5)*/@TableField(exist = false)@ExcelProperty(value = "項目靠譜程度",index = 26)@ApiModelProperty(value = "項目靠譜程度", required = true)private String star;/*** contract_cash_count, 合同金額*/@TableField(exist = false)@ExcelProperty(value = "合同金額(萬元)",index = 27)@ApiModelProperty(value = "合同金額", required = true)private String contractCashCount;/*** realcontract_cash, 合同實際金額*/@TableField(exist = false)@ExcelProperty(value = "合同實際金額(萬元)",index = 28)@ApiModelProperty(value = "合同實際金額", required = true)private String realcontractCash;/*** contract_mode, 合同模式(0.分期付款1.背靠背式2:賒賬)*/@TableField(exist = false)@ExcelProperty(value = "合同模式",index = 29)@ApiModelProperty(value = "合同模式(0.分期付款1.背靠背式2:賒賬)", required = true)private String contractMode;/*** intexamine_time, 初驗收時間*/@TableField(exist = false)@ExcelProperty(value = "初驗收時間(yyyy/mm/dd)",index =30)@ApiModelProperty(value = "初驗收時間", required = true)private Date intexamineTime;/*** init_cash, 初步收入金額*/@TableField(exist = false)@ExcelProperty(value = "初步收入金額(萬元)",index =31)@ApiModelProperty(value = "初步收入金額", required = true)private String initCash;/*** endexamine_time, 最終驗收時間*/@TableField(exist = false)@ExcelProperty(value = "最終驗收時間(yyyy/mm/dd)",index =32)@ApiModelProperty(value = "最終驗收時間", required = true)private Date endexamineTime;/*** end_cash, 最終金額*/@TableField(exist = false)@ExcelProperty(value = "最終金額(萬元)",index =33)@ApiModelProperty(value = "最終金額", required = true)private String endCash;/*** receive_cash_time, 收款最終時間*/@TableField(exist = false)@ExcelProperty(value = "收款日期(yyyy/mm/dd)",index =34)@ApiModelProperty(value = "收款最終時間", required = true)private Date receiveCashTime;/*** contract_deposit, 合同預付款(定金)*/@TableField(exist = false)@ExcelProperty(value = "預付款(萬元)",index =35)@ApiModelProperty(value = "合同預付款(定金)", required = true)private String contractDeposit;/*** proj_state, 項目狀態(0項目進行中/1暫停項目/2催款中/3已完成需催款/4已清項目)*/@TableField(exist = false)@ExcelProperty(value = "項目狀態",index =36)@ApiModelProperty(value = "項目狀態(0項目進行中/1暫停項目/2催款中/3已完成需催款/4已清項目)", required = true)private String projState;/*** back_cash, 回款跟催狀態(1.催款中2.已完成催款3.已清項目4.異常5.拖款)*/@TableField(exist = false)@ExcelProperty(value = "回款跟催階段",index =37)@ApiModelProperty(value = "回款跟催狀態(0. 正在催款 1. 常規(預計三個月內收款 ) 2. 異常(預計超半年催款) 3.拖款(預計3~6個月回款))", required = true)private String backCash;/*** market_commision, 市場提成系數*/@TableField(exist = false)@ExcelProperty(value = "市場提成系數",index =38)@ApiModelProperty(value = "市場提成系數", required = true)private String marketCommision;/*** commision_month, 市場提成月數*/@TableField(exist = false)@ExcelProperty(value = "市場提成月份",index =39)@ApiModelProperty(value = "市場提成月數", required = true)private String commisionMonth;/*** feedback, 具體反饋(0.成果質量1.服務態度2.過程技術配合3.時間配合4.交付時間)*/@TableField(exist = false)@ExcelProperty(value = "具體反饋",index =40)@ApiModelProperty(value = "具體反饋(0.成果質量1.服務態度2.過程技術配合3.時間配合4.交付時間)", required = true)private String feedback;/*** remark, 備注(項目注意事宜)*/@TableField(exist = false)@ExcelProperty(value = "備注",index =41)@ApiModelProperty(value = "備注(項目注意事宜)", required = true)private String remark;/*** detail_need,詳細需求*/@TableField(exist = false)@ExcelProperty(value = "詳細需求",index =42)@ApiModelProperty(value = "詳細需求", required = true)private String detailNeed;}2.在controller層調用ExcelUtils工具類下的customerInformationReadExcel()方法。
/*** 根據客戶信息導入模板批量導入** @param* @return* @throws Exception*/@PreAuthorize("hasPermit('sale:client')")@RequestMapping(value = "/customerInformationReadExcel", method = RequestMethod.POST, produces = "application/octet-stream")@ApiOperation(value = "客戶信息導入(按照模板導入)", tags = {"銷售模塊", "客戶信息導入(按照模板導入)"})public Result customerInformationReadExcel(@RequestPart @RequestParam(value = "file", required = false) MultipartFile file)throws Exception {try {ExcelUtils.customerInformationReadExcel(file.getInputStream());return Result.success(ResultCode.成功, ResultCode.成功.getCode());} catch (Exception e) {return Result.error(ResultCode.失敗.getMsg(), ResultCode.失敗.getCode(), null);}}3.進入ExcelUtils工具類編寫customerInformationReadExcel()方法,其中需要調用到CustomManageListener()監聽器也可稱之為解析器。
/*** 根據客戶信息導入模板批量導入* @param inputStream*/public static void customerInformationReadExcel(InputStream inputStream) {EasyExcel.read(inputStream, CustomManageAndCustomerInformationReadVO.class,new CustomManageListener()).registerConverter(new LocalDateTimeConverter()).sheet().doRead();}4.導入的難點就在于監聽器的編寫,如若導入的數據屬于一張表還不難,重點是我這次做的是多表的,需要進行連表操作,調用其他表的mapper和service。不會做就覺得難。做了覺得也還行不是特別難,就像地上本沒有路走的人多了也就成了路。監聽器中調用了公共枚舉中文轉數字的方法。
package com.theiavis.workcloud.project.sale.enums;import com.alibaba.excel.context.AnalysisContext; import com.alibaba.excel.exception.ExcelDataConvertException; import com.alibaba.excel.read.listener.ReadListener; import com.alibaba.excel.util.ListUtils; import com.alibaba.excel.util.StringUtils; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.theiavis.security.jwt.UserOperator; import com.theiavis.workcloud.project.agreement.bean.ProjAgreement; import com.theiavis.workcloud.project.agreement.mapper.ProjAgreementMapper; import com.theiavis.workcloud.project.agreement.service.IProjAgreementService; import com.theiavis.workcloud.project.dingtalk.bean.User; import com.theiavis.workcloud.project.dingtalk.mapper.UserMapper; import com.theiavis.workcloud.project.proj.VO.proj.ProjIdOutputVo; import com.theiavis.workcloud.project.proj.VO.proj.ProjInsertVO; import com.theiavis.workcloud.project.proj.bean.Project; import com.theiavis.workcloud.project.proj.mapper.ProjectMapper; import com.theiavis.workcloud.project.proj.service.ProjectService; import com.theiavis.workcloud.project.sale.bean.CustomManage; import com.theiavis.workcloud.project.sale.mapper.CustomManageMapper; import com.theiavis.workcloud.project.sale.service.ICustomManageService; import com.theiavis.workcloud.project.sale.vo.CustomManageAndCustomerExportVO; import com.theiavis.workcloud.project.sale.vo.CustomManageAndCustomerInformationReadVO; import lombok.NoArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Lazy; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional;import javax.annotation.PostConstruct; import java.util.List; import java.util.logging.Logger;@Slf4j @Component public class CustomManageListener implements ReadListener<CustomManageAndCustomerInformationReadVO> {private static final Logger logger = Logger.getLogger(CustomManageListener.class.getName());/*** 每隔5條存儲數據庫,實際使用中可以100條,然后清理list ,方便內存回收*/private static final int BATCH_COUNT = 100;/*** 緩存的數據*/private List<CustomManageAndCustomerInformationReadVO> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);@AutowiredICustomManageService iCustomManageService;//相當于注冊到spring的一個bean@AutowiredUserOperator userOperator;@AutowiredUserMapper userMapper;//相當于注冊到spring的一個bean@AutowiredIProjAgreementService iProjAgreementService;//相當于注冊到spring的一個bean@AutowiredProjectService projectService;//相當于注冊到spring的一個bean//把他自身的類實例化,并定義成靜態類public static CustomManageListener customManageListener;@PostConstructpublic void init(){//當前指針去指向這個類的對象,因為spring容器里面有相同的對象customManageListener =this;}/*** 這個每一條數據解析都會來調用** @param customManageAndCustomerInformationReadVO one row value. Is is same as {@link AnalysisContext#readRowHolder()}* @param analysisContext*/@Transactional(rollbackFor = Exception.class)@Overridepublic void invoke(CustomManageAndCustomerInformationReadVO customManageAndCustomerInformationReadVO, AnalysisContext analysisContext) {logger.info("解析到一條數據:{}");cachedDataList.add(customManageAndCustomerInformationReadVO);// 達到BATCH_COUNT了,需要去存儲一次數據庫,防止數據幾萬條數據在內存,容易OOMif (cachedDataList.size() >= BATCH_COUNT) {saveData();// 存儲完成清理 listcachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);}}@Transactional(rollbackFor = Exception.class)public void saveData() {cachedDataList.stream().forEach(i->{logger.info("{}條數據,開始存儲數據庫!");try { // String 數字=StatusEnum.getEnumNum("錯誤","Source"); // User createId=customManageListener.userMapper.selectOne(new QueryWrapper<User>().groupBy("user_id").like("name",i.getCreaterName()));//查詢出的結果絕對有一個用selectOne()方法(如若有多條數據就會報錯),QueryWrapper<User>()方法是MybatisPlus函數的用法,實現查詢的對象封裝操作類。groupBy()分組,like()模糊查詢。根據followId(也就是user_id)查詢對應的followName。主表中沒有followName,只有followId,所以在user表(userMapper)中查詢對應的name。User followId=customManageListener.userMapper.selectOne(new QueryWrapper<User>().groupBy("user_id").like("name",i.getFollowName()));//鏈式編程。數據存在主表(custom_manage)中CustomManage customManage=new CustomManage().setFollowId(followId.getUserId()!=null?followId.getUserId():null).setSaleTimeYear(i.getSaleTimeYear()).setSaleTimeMonth(i.getSaleTimeMonth()).setCompany(i.getCompany()).setCustomType(StatusEnum.getEnumNum(i.getCustomType(),"CustomType")).setCity(i.getCity()).setCustomDepartment(i.getCustomDepartment()).setContact(i.getContact()).setEmail(i.getEmail()).setMobile(i.getMobile()).setCustomSource(StatusEnum.getEnumNum(i.getCustomSource(),"CustomSource"));if (StringUtils.isNotBlank(i.getProjName())){//數據存儲在project次表中ProjIdOutputVo projIdOutputVo =customManageListener.projectService.insertProj(new ProjInsertVO().setProjName(i.getProjName()));//數據存儲在proj_agreement次表中int projAgreementId=customManageListener.iProjAgreementService.addProjAgreement(new ProjAgreement().setStage(StatusEnum.getEnumNum(i.getStage(),"Stage")).setSource(StatusEnum.getEnumNum( i.getSource(),"Source")).setAddress(i.getAddress()).setProjectType(StatusEnum.getEnumNum( i.getProjectType(),"ProjectType")).setFollowResult(StatusEnum.getEnumNum( i.getFollowResult(),"FollowResult")).setFollowFailResult(i.getFollowFailResult()).setPlanStartTime(i.getPlanStartTime()).setProjNeed(i.getProjNeed()).setPlanEndTime(i.getPlanEndTime()).setProductCount(i.getProductCount()).setContractCash(i.getContractCash()).setPlaceContract(StatusEnum.getEnumNum(i.getPlaceContract(),"PlaceContract")).setEffectPj(StatusEnum.getEnumNum(i.getEffectPj(),"EffectPj")).setProjProgress(StatusEnum.getEnumNum(i.getProjProgress(),"ProjProgress")).setStar(i.getStar()).setContractCashCount(i.getContractCashCount()).setRealcontractCash(i.getRealcontractCash()).setContractMode(StatusEnum.getEnumNum(i.getContractMode(),"ContractMode")).setIntexamineTime(i.getIntexamineTime()).setInitCash(i.getInitCash()).setEndexamineTime(i.getEndexamineTime()).setEndCash(i.getEndCash()).setReceiveCashTime(i.getReceiveCashTime()).setContractDeposit(i.getContractDeposit()).setProjState(StatusEnum.getEnumNum(i.getProjState(),"ProjState")).setBackCash(StatusEnum.getEnumNum(i.getBackCash(),"BackCash")).setMarketCommision(i.getMarketCommision()).setCommisionMonth(i.getCommisionMonth()).setFeedback(StatusEnum.getEnumNum(i.getFeedback(),"Feedback")).setRemark(i.getRemark()).setDetailNeed(i.getDetailNeed()));customManageListener.iCustomManageService.addCustomManage(customManage.setProjNum(projIdOutputVo.getProjNum()).setAgreementId(projAgreementId));//指定到靜態的Usermapper注入的對象}} catch (Exception e) {e.printStackTrace();}});logger.info("存儲數據庫成功!");}/*** 在轉換異常 獲取其他異常下會調用本接口。拋出異常則停止讀取。如果這里不拋出異常則 繼續讀取下一行。* // * @param exception // * @param context* @throws Exception*/ // @Override // public void onException(Exception exception, AnalysisContext context) { // log.error("解析失敗,但是繼續解析下一行:{}", exception.getMessage()); // // 如果是某一個單元格的轉換異常 能獲取到具體行號 // // 如果要獲取頭的信息 配合invokeHeadMap使用 // if (exception instanceof ExcelDataConvertException) { // ExcelDataConvertException excelDataConvertException = (ExcelDataConvertException)exception; // log.error("第{}行,第{}列解析異常,數據為:{}", excelDataConvertException.getRowIndex(), // excelDataConvertException.getColumnIndex(), excelDataConvertException.getCellData()); // } // }@Overridepublic void doAfterAllAnalysed(AnalysisContext analysisContext) {// 這里也要保存數據,確保最后遺留的數據也存儲到數據庫saveData();logger.info("所有數據解析完成!");} }5.進入公共枚舉類,編寫中文轉數字的getEnumNum()方法,實現中文獲取數字,導入,(從excel中導入數據至數據庫)。
package com.theiavis.workcloud.project.sale.enums;import com.baomidou.mybatisplus.annotation.EnumValue; import com.fasterxml.jackson.annotation.JsonValue; import lombok.Getter; import lombok.NoArgsConstructor;/**** @author lyh and xql*/ @NoArgsConstructor @Getter public enum StatusEnum {/*** 客戶來源(頁面名稱從0開始) 項目信息來源(數據庫名稱從1開始)*/信息("Source","0"),公司轉交("Source","1"),自我開拓("Source","2"),合作客戶轉介紹("Source","3"),絲路分公司("Source","4"),展會信息("Source","5"),協會資源轉換("Source","6"),其他渠道("Source","7"),/*** 項目類型 頁面字段與數據庫不符*/數字大屏("ProjectType","0"),數字沙盤("ProjectType","1"),數字展項("ProjectType","2"),數字展廳("ProjectType","3"),CIM("ProjectType","4"),VRXR("ProjectType","5"),其他("ProjectType","6"),/*** 客戶類型*/商業公司("CustomType","0"),政府("CustomType","1"),地產商("CustomType","2"),規劃院("CustomType","3"),/*** 跟進結果*/成功("FollowResult","0"),失敗("FollowResult","1"),跟進中("FollowResult","2"),/*** 新舊客戶類型*/移交客戶("CustomSource","0"),新客戶("CustomSource","1"),/*** 是否簽訂保密協議*/未簽約("PlaceContract","0"),已簽約("PlaceContract","1"),/*** 是否當地影響力*/否("EffectPj","0"),是("EffectPj","1"),/*** 項目進度*/前期介入("ProjProgress","0"),項目報價("ProjProgress","1"),關鍵人物接觸("ProjProgress","2"),方案制作階段("ProjProgress","3"),方案匯報("ProjProgress","4"),DEMO制作("ProjProgress","5"),投標階段("ProjProgress","6"),簽約階段("ProjProgress","7"),/*** 合同模式*/背靠背("ContractMode","0"),分期付款("ContractMode","1"),賒銷("ContractMode","2"),/*** 項目狀態*/項目進行中("ProjState","0"),暫停項目("ProjState","1"),催款中("ProjState","2"),已完成需催款("ProjState","3"),已清項目("ProjState","4"),/*** 回款跟催階段*/正在催款("BackCash","0"),常規("BackCash","1"),異常("BackCash","2"),拖款("BackCash","3"),/*** 具體反饋*/成果質量("Feedback","0"),服務態度("Feedback","1"),過程技術配合("Feedback","2"),時間配合("Feedback","3"),交付時間("Feedback","4"),/*** 所處階段,所屬階段*/商機線索("Stage","0"),在談項目("Stage","1"),簽約項目("Stage","2"),已歸檔("Stage","3"),/*** 狀態*/新領取("Status","0"),占用("Status","1"),新歸還("Status","2"),空閑("Status","3"),接收中("Status","4"),/*** 資產類型0筆記本1顯示器2ipad3AR/VA設備4相機5鼠標6其他*/筆記本("Type","0"),顯示器("Type","1"),ipad("Type","2"),AR或VA設備("Type","3"),相機("Type","4"),鼠標("Type","5"),其他設備("Type","6"),/*** 申報視圖的申報狀態*/未申報("DeclareStatus","0"),已申報("DeclareStatus","1"),;/*** 字段 (英文)*/@EnumValueprivate String key;/*** 屬性 (數字)*/@JsonValueprivate String value;StatusEnum(String key, String value) {this.value = value;this.key = key;}public String getKey() {return key;}public String getValue() {return value;}/*** 數字獲取中文,導出,從數據庫中導出數據至excel* @param key 英文,對應bean的字段名* @param value 數字,對應數據庫的0123的標識注釋* @return*/public static String getEnum(String key,String value){//用數組存放這些屬性(也就是枚舉的值)StatusEnum[] applicationStateEnums = values();//循環判斷key和value是否相等,相等就返回枚舉中對應的中文namefor (StatusEnum itemEnum : applicationStateEnums) {if (itemEnum.key.equals(key) && itemEnum.value.equals(value)) {if (key.equals("Source")&&value!=null){return itemEnum.name().replace("信息","400信息");}else{return itemEnum.name();}}}return null;}/*** 中文獲取數字,導入,從excel中導入數據至數據庫中* @param name 中文,枚舉中有定義,對應模板的下拉選項* @param key 英文,對應bean的字段名* @return*/public static String getEnumNum(String name,String key){//用數組存放這些屬性(也就是枚舉的值)StatusEnum[] applicationStateEnums = values();//循環判斷name和key是否相等,相等就返回枚舉中對應的數字valuefor (StatusEnum itemEnum : applicationStateEnums) {if (key.equals("Source")&& name.equals("400信息")){return "0";}if (itemEnum.name().equals(name)&& itemEnum.key.equals(key)) {return itemEnum.value;}}return null;}}6.進入主表的mappe進行連表操作,需要用到的字段都要在前面標明是哪個表里的什么字段as別名是什么,進行連表的字段還需在主表也就是本模塊的實體類中標注注解此字段不在本表中,不然導出的數據會出現有些字段無數據。
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.theiavis.workcloud.project.sale.mapper.CustomManageMapper"><!-- 通用設置 --><!-- 通用查詢列 --><sql id="Base_Column_List">a.id,a.sale_time_year,a.sale_time_month,a.proj_num,a.follow_id,a.create_id,a.company,a.custom_type,a.city,a.custom_department,a.contact,a.mobile,a.email,a.custom_source,a.custom_id,a.permit_code,a.dept_id,a.agreement_id,a.create_time,a.is_delete</sql><select id="findCustomManageByAll" resultType="com.theiavis.workcloud.project.sale.vo.CustomManageAndProjectVO">SELECT<include refid="Base_Column_List"/>,a.custom_type as CustomType,b.proj_name,f.name as follow_name,d.name as creater_name,c.stage,c.source as Source,c.address,c.project_type,c.follow_result,c.follow_fail_result,c.plan_start_time,c.proj_need,c.plan_end_time,c.product_count,c.contract_cash,c.place_contract,c.effect_pj,c.proj_progress,c.star,c.contract_cash_count,c.realcontract_cash,c.contract_mode,c.intexamine_time,c.init_cash,c.endexamine_time,c.end_cash,c.receive_cash_time,c.contract_deposit,c.proj_state,c.back_cash,c.market_commision,c.commision_month,c.feedback,c.remark,c.detail_need,d.avatar as creater_avatar,f.avatar as follow_avatar<include refid="Condition"/></select><sql id="Condition">FROM custom_manage AS aLEFT JOIN project b On b.proj_num=a.proj_numLEFT JOIN proj_agreement c ON c.id =a.agreement_idLEFT JOIN user d On d.user_id=a.create_idLEFT JOIN user f On f.user_id=a.follow_idwhere<if test="customManage!=null and customManage.id !=null and customManage.id !=''">a.id =#{customManage.id}and</if><if test="customManage!=null and customManage.stage !=null and customManage.stage !=''">c.stage likeCONCAT('%',#{customManage.stage}, '%') and</if><if test="customManage!=null and customManage.company !=null and customManage.company !=''">a.company likeCONCAT('%',#{customManage.company}, '%') or</if><if test="customManage!=null and customManage.projName !=null and customManage.projName !=''">b.proj_name likeCONCAT('%',#{customManage.projName}, '%') and</if><if test="customManage!=null and customManage.saleTimeYear !=null and customManage.saleTimeYear !=''">a.sale_time_year likeCONCAT('%',#{customManage.saleTimeYear}, '%') and</if><if test="customManage!=null and customManage.saleTimeMonth !=null and customManage.saleTimeMonth !=''">a.sale_time_month likeCONCAT('%',#{customManage.saleTimeMonth}, '%') and</if><if test="customManage!=null and customManage.followId !=null and customManage.followId !=''">a.follow_id =#{customManage.followId} and</if><if test="customManage!=null and customManage.createId !=null and customManage.createId !=''">a.create_id =#{customManage.createId} and</if><if test="customManage!=null and customManage.userId !=null and customManage.userId !=''">(a.create_id =#{customManage.userId} or a.follow_id = #{customManage.userId}) and</if>a.is_delete=0 and a.idOrder By a.create_time Desc</sql>總結
以上是生活随笔為你收集整理的枚举中文转数字并easyexcel导入(读取Read)数据至数据库,用监听器解决导入关联多表的问题的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 我和兄弟连
- 下一篇: 如何用一行代码实现网页变灰效果?