拆分导入

This commit is contained in:
gaojiabao
2023-04-03 21:11:11 +08:00
parent c52c720884
commit d3c152f5b4
10 changed files with 870 additions and 263 deletions
@@ -6,6 +6,7 @@ import cn.hutool.core.util.ZipUtil;
import com.adc.da.att.controller.AttFileEOController;
import com.adc.da.att.entity.AttFileEO;
import com.adc.da.att.service.IAttFileEOService;
import com.adc.da.att.util.CommonExportUtil;
import com.adc.da.base.web.BaseController;
import com.adc.da.common.ConvertHtml2Excel;
import com.adc.da.common.FileUnZip;
@@ -546,8 +547,7 @@ public class SarFileSplitItemsEOController extends BaseController<SarFileSplitIt
// 导入参数设置,默认即可
ImportParams params = new ImportParams();
try {
String fields[] = {"条款号", "条款名称","内容简介","责任部门",
"FO","责任工程师","SVPPS","适用车辆类型","要求类型","企标覆盖关系"};
String fields[] = {"条款号", "条款名称","条款内容","条款附件"};
params.setImportFields(fields);
List<SarFileSplitItemsImportDto> result = new ArrayList<>();
// 解析excel,并返回校验信息
@@ -583,6 +583,12 @@ public class SarFileSplitItemsEOController extends BaseController<SarFileSplitIt
//是则不读取
continue;
}
//判断此行数据是否全部为空
if(sarStandImportDto.getItemsNum().contains("模板说明")){
i++;
//是则不读取
continue;
}
i = 0;
datasUpdate.add(sarStandImportDto);
}
@@ -658,5 +664,26 @@ public class SarFileSplitItemsEOController extends BaseController<SarFileSplitIt
return Result.error("0", "该条数据标准号在标准库中不存在");
}
//导入模板下载
@ApiOperation(value = "拆分导入模板下载")
@GetMapping(value = "/exportTemplate")
public void exportTemplate(HttpServletResponse response, HttpServletRequest request) throws Exception {
String[] headers = { "条款号","条款名称","条款内容","条款附件"};
try{
String fileName = "拆分导入模板下载/导入模板";
StringBuilder descBuilder = new StringBuilder()
.append("模板说明:")
.append("\n")
.append("1:条款号,条款名称,条款内容不能为空")
.append("\n")
.append("2:将附件存放在zip格式的文件夹中,名称与后缀输入于附件中即可")
.append("\n")
.append("3:图片格式格式为jpg")
.append("\n");
//生成模板
CommonExportUtil.exportTemplate(fileName,headers,descBuilder.toString(), response,request);
}catch (Exception e){
throw new AdcDaBaseException("下载文件失败,请重试");
}
}
}
@@ -1,12 +1,14 @@
package com.adc.da.slrs.standardSplit.dto;
import cn.afterturn.easypoi.excel.annotation.Excel;
import lombok.Data;
/**
* @Description:
* @Author: yangxuenan
* date: 2020/5/9 14:40
*/
@Data
public class SarFileSplitItemsImportDto {
@Excel(name = "条款号", orderNum = "1")
private String itemsNum;
@@ -14,32 +16,35 @@ public class SarFileSplitItemsImportDto {
@Excel(name = "条款名称", orderNum = "1")
private String itemsName;
@Excel(name = "内容简介", orderNum = "1")
@Excel(name = "条款附件", orderNum = "1")
private String itermsConditions;
@Excel(name = "责任部门", orderNum = "1")
private String responsibleUnit;
// @Excel(name = "责任部门", orderNum = "1")
// private String responsibleUnit;
@Excel(name = "条款内容", orderNum = "1")
private String mag;
// @Excel(name = "责任部门", orderNum = "1")
private String newcarPutTime;
// private String newcarPutTime;
@Excel(name = "FO", orderNum = "1")
private String fo;
// @Excel(name = "FO", orderNum = "1")
// private String fo;
@Excel(name = "责任工程师", orderNum = "1")
private String dutyEngineer;
// @Excel(name = "责任工程师", orderNum = "1")
// private String dutyEngineer;
//
// @Excel(name = "SVPPS", orderNum = "1")
// private String svpps;
@Excel(name = "SVPPS", orderNum = "1")
private String svpps;
@Excel(name = "适用车辆类型", orderNum = "1")
private String applyArctic;
@Excel(name = "要求类型", orderNum = "1")
private String claimType;
@Excel(name = "企标覆盖关系", orderNum = "1")
private String busStandCover;
// @Excel(name = "适用车辆类型", orderNum = "1")
// private String applyArctic;
//
// @Excel(name = "要求类型", orderNum = "1")
// private String claimType;
//
// @Excel(name = "企标覆盖关系", orderNum = "1")
// private String busStandCover;
@@ -56,93 +61,4 @@ public class SarFileSplitItemsImportDto {
// private String relevanceFile;
//
// private String relevanceFileName;
public String getItemsNum() {
return itemsNum;
}
public void setItemsNum(String itemsNum) {
this.itemsNum = itemsNum;
}
public String getItemsName() {
return itemsName;
}
public void setItemsName(String itemsName) {
this.itemsName = itemsName;
}
public String getItermsConditions() {
return itermsConditions;
}
public void setItermsConditions(String itermsConditions) {
this.itermsConditions = itermsConditions;
}
public String getResponsibleUnit() {
return responsibleUnit;
}
public void setResponsibleUnit(String responsibleUnit) {
this.responsibleUnit = responsibleUnit;
}
public String getNewcarPutTime() {
return newcarPutTime;
}
public void setNewcarPutTime(String newcarPutTime) {
this.newcarPutTime = newcarPutTime;
}
public String getFo() {
return fo;
}
public void setFo(String fo) {
this.fo = fo;
}
public String getDutyEngineer() {
return dutyEngineer;
}
public void setDutyEngineer(String dutyEngineer) {
this.dutyEngineer = dutyEngineer;
}
public String getSvpps() {
return svpps;
}
public void setSvpps(String svpps) {
this.svpps = svpps;
}
public String getApplyArctic() {
return applyArctic;
}
public void setApplyArctic(String applyArctic) {
this.applyArctic = applyArctic;
}
public String getClaimType() {
return claimType;
}
public void setClaimType(String claimType) {
this.claimType = claimType;
}
public String getBusStandCover() {
return busStandCover;
}
public void setBusStandCover(String busStandCover) {
this.busStandCover = busStandCover;
}
}
@@ -15,6 +15,9 @@ import com.adc.da.common.ReadWordTable;
import com.adc.da.slrs.standardSplit.entity.*;
import com.adc.da.slrs.standardSplit.service.SarFileSplitInfoEOService;
import com.adc.da.sys.common.SelectionResult;
import com.adc.da.sys.dao.DicTypeEODao;
import com.adc.da.sys.entity.DicTypeEO;
import com.adc.da.sys.service.IDicTypeEOService;
import com.adc.da.sys.util.LoginUserUtil;
import com.adc.da.sys.util.UUIDUtils;
import org.apache.commons.collections4.CollectionUtils;
@@ -91,6 +94,10 @@ public class SarFileSplitInfoEOServiceImpl implements SarFileSplitInfoEOService
private SarFileSplitItemsParamsEODao sarFileSplitItemsParamsEODao;
@Autowired
private SarFileSplitInfoEODao dao;
@Autowired
private DicTypeEODao dicTypeEODao;
@Autowired
private IDicTypeEOService dicTypeEOService;
@Override
public List<SarFileSplitInfoEO> queryByPage(BasePage page) throws Exception{
@@ -735,6 +742,13 @@ public class SarFileSplitInfoEOServiceImpl implements SarFileSplitInfoEOService
// }
}
}
for (SarFileSplitInfoEO data : rows){
List<DicTypeEO> dicTypeEO = dicTypeEODao.selectPidByCode(data.getFileType());
if(dicTypeEO!=null){
data.setFileTypeShow(dicTypeEO.get(0).getDicTypeName());
}
}
return rows;
}
@@ -71,6 +71,9 @@ public class SarFileSplitItemsEOServiceImpl implements SarFileSplitItemsEOServic
@Autowired
private SarFileSplitInfoEOService sarFileSplitInfoEOService;
@Value("${elasticsearch.img}")
private String elasticsearchImg;//图片拆分自调地址
@Override
public Map<String, Object> getByPage(SarFileSplitItemsEOPage page) {
@@ -468,7 +471,6 @@ public class SarFileSplitItemsEOServiceImpl implements SarFileSplitItemsEOServic
}else {
infoId = UUIDUtils.randomUUID20();
}
//验证导入数据是否符合规则
Map map = validateImportDatas(list,filepath);
boolean isOk = (boolean) map.get("result");
if (!isOk) {
@@ -530,12 +532,13 @@ public class SarFileSplitItemsEOServiceImpl implements SarFileSplitItemsEOServic
List<File> nowfilelist = FileUnZip.readFileByFilename(filepath, valArr[i]);
if (nowfilelist != null && !nowfilelist.isEmpty()) {
AttFileVo attFileVo = attFileEOService.saveFileInfo(nowfilelist.get(0));
if(attFileVo!=null){
if (attFileVo != null) {
isText = false;
String path = "file" + attFileVo.getFilePath()+attFileVo.getFileName();
String imgCon = "<img class=\'wordImg\' src=\'" + path + "\'>";
//String path = "E:/data/slrs/file" + attFileVo.getFilePath()+attFileVo.getOldFileName();
String pathSrc = elasticsearchImg + "/api/att/attFile/getFileInfo?fileId=" + attFileVo.getId();
String imgCon = "<img class=\'wordImg\' src=\'" + pathSrc + "\'>";
valEO.setType("IMG");
valEO.setItemContent(imgCon);
valEO.setItemContent(imgCon + "<p>" + importDto.getMag() + "<p>");
}
}
if (isText) {
@@ -564,12 +567,13 @@ public class SarFileSplitItemsEOServiceImpl implements SarFileSplitItemsEOServic
List<File> nowfilelist = FileUnZip.readFileByFilename(filepath, valArr[i]);
if (nowfilelist != null && !nowfilelist.isEmpty()) {
AttFileVo attFileVo = attFileEOService.saveFileInfo(nowfilelist.get(0));
if(attFileVo!=null){
if (attFileVo != null) {
isText = false;
String path = "file" + attFileVo.getFilePath()+attFileVo.getFileName();
String imgCon = "<img class=\'wordImg\' src=\'" + path + "\'>";
//String path = "E:/data/slrs/file" + attFileVo.getFilePath()+attFileVo.getOldFileName();
String pathSrc = elasticsearchImg + "/api/att/attFile/getFileInfo?fileId=" + attFileVo.getId();
String imgCon = "<img class=\'wordImg\' src=\'" + pathSrc + "\'>";
valEO.setType("IMG");
valEO.setItemContent(imgCon);
valEO.setItemContent(imgCon + "<p>" + importDto.getMag() + "<p>");
}
}
if (isText) {
@@ -600,12 +604,13 @@ public class SarFileSplitItemsEOServiceImpl implements SarFileSplitItemsEOServic
List<File> nowfilelist = FileUnZip.readFileByFilename(filepath, valArr[i]);
if (nowfilelist != null && !nowfilelist.isEmpty()) {
AttFileVo attFileVo = attFileEOService.saveFileInfo(nowfilelist.get(0));
if(attFileVo!=null){
if (attFileVo != null) {
isText = false;
String path = "file" + attFileVo.getFilePath()+attFileVo.getFileName();
String imgCon = "<img class=\'wordImg\' src=\'" + path + "\'>";
//String path = "E:/data/slrs/file" + attFileVo.getFilePath()+attFileVo.getOldFileName();
String pathSrc = elasticsearchImg + "/api/att/attFile/getFileInfo?fileId=" + attFileVo.getId();
String imgCon = "<img class=\'wordImg\' src=\'" + pathSrc + "\'>";
valEO.setType("IMG");
valEO.setItemContent(imgCon);
valEO.setItemContent(imgCon + "<p>" + importDto.getMag() + "<p>");
}
}
if (isText) {
@@ -629,6 +634,7 @@ public class SarFileSplitItemsEOServiceImpl implements SarFileSplitItemsEOServic
sarFileSplitInfoEO.setValidFlag(0);
sarFileSplitInfoEO.setResult("1");
sarFileSplitInfoEO.setModifyUser(LoginUserUtil.getUserId());
sarFileSplitInfoEO.setStandId(sarFileSplitInfoEO.getStandId());
sarFileSplitInfoEOService.insertSelective(sarFileSplitInfoEO);
}
@@ -640,6 +646,14 @@ public class SarFileSplitItemsEOServiceImpl implements SarFileSplitItemsEOServic
menuPidMap.put("总目录",menuid );
}
for (SarFileSplitItemsEO itemsEO : addItemsEOList) {
List<SarFileSplitItemsValEO> itemValEOList = itemsEO.getItemValEOList();
if(itemValEOList!=null){
String tupian = "";
for (SarFileSplitItemsValEO data : itemValEOList){
tupian = tupian+data.getItemContent();
}
itemsEO.setItermsConditions(tupian);
}
String menuIdT = createItemsInfo(itemsEO,infoId,countSuccess,menuPidMap);
menuPidMap.put(itemsEO.getItemsNum(),menuIdT);
countSuccess++;
@@ -724,6 +738,11 @@ public class SarFileSplitItemsEOServiceImpl implements SarFileSplitItemsEOServic
int num = 0; //记录是第几条数据
//循环验证数据
for (SarFileSplitItemsImportDto dto : datas) {
if(dto.getItemsNum().contains("模板说明")){
continue;
}
i++;
int countError = 0; //记录失败数据数量
DicTypeEO dic = new DicTypeEO();
@@ -755,148 +774,151 @@ public class SarFileSplitItemsEOServiceImpl implements SarFileSplitItemsEOServic
countError++;
}
}
String saveApplyCode = "";
if (StringUtils.isNotEmpty(dto.getApplyArctic())) {
dto.setApplyArctic(dto.getApplyArctic().replace("", ","));
String applys[] = dto.getApplyArctic().split(",");
if(applys.length>20){
errorMsg += "适用车型选项不能超过20个;";
countError++;
} else if (dto.getApplyArctic().length() > 500) {
errorMsg += "适用车型不能超过500个字符;";
countError++;
} else {
Set set = new HashSet();
for (int a = 0; a < applys.length; a++) {
dic.setDicTypeName(applys[a]);
dic.setDicTypeCode("ENERGYTYPES");
getDic = dicTypeEODao.getDicTypeByDicTypeName(dic);
if (getDic.size() == 1) {
saveApplyCode += getDic.get(0).getDicTypeCode() + ",";
} else if (getDic.size() > 0) {
errorMsg += "适用车型" + applys[a] + "不明确;";
countError++;
break;
} else {
errorMsg += "适用车型" + applys[a] + "不存在;";
countError++;
break;
}
set.add(applys[a]);
if (a==applys.length-1 && applys.length != set.size()){
errorMsg += "适用车型存在重复数据;";
countError++;
}
}
if (!saveApplyCode.equals("")){
dto.setApplyArctic(saveApplyCode.substring(0,saveApplyCode.length()-1));
}
}
}
if(!claimStypelist.contains(dto.getClaimType())) {
if (StringUtils.isNotEmpty(dto.getClaimType())) {
dic.setDicTypeName(dto.getClaimType());
dic.setDicTypeCode("REQUESTTYPE");
if (dto.getClaimType().length() > 500) {
errorMsg += "要求类型不能超过500个字符;";
countError++;
} else {
getDic = dicTypeEODao.getDicTypeByDicTypeName(dic);
Set set = new HashSet();
if (getDic != null) {
if (getDic.size() == 1) {
dto.setClaimType(getDic.get(0).getDicTypeCode());
claimStypelist.add(getDic.get(0).getDicTypeCode());
} else if (getDic.size() > 0) {
errorMsg += "要求类型不明确;";
countError++;
} else {
errorMsg += "要求类型不存在;";
countError++;
}
} else {
errorMsg += "要求类型不存在;";
countError++;
}
}
}
}
if(StringUtils.isNotEmpty(dto.getItermsConditions())){
if(dto.getItermsConditions().length() > 50000){
errorMsg += "内容简介不能超过50000个字符;";
// String saveApplyCode = "";
// if (StringUtils.isNotEmpty(dto.getApplyArctic())) {
// dto.setApplyArctic(dto.getApplyArctic().replace("", ","));
// String applys[] = dto.getApplyArctic().split(",");
// if(applys.length>20){
// errorMsg += "适用车型选项不能超过20个;";
// countError++;
// } else if (dto.getApplyArctic().length() > 500) {
// errorMsg += "适用车型不能超过500个字符;";
// countError++;
// } else {
// Set set = new HashSet();
// for (int a = 0; a < applys.length; a++) {
// dic.setDicTypeName(applys[a]);
// dic.setDicTypeCode("ENERGYTYPES");
// getDic = dicTypeEODao.getDicTypeByDicTypeName(dic);
// if (getDic.size() == 1) {
// saveApplyCode += getDic.get(0).getDicTypeCode() + ",";
// } else if (getDic.size() > 0) {
// errorMsg += "适用车型" + applys[a] + "不明确;";
// countError++;
// break;
// } else {
// errorMsg += "适用车型" + applys[a] + "不存在;";
// countError++;
// break;
// }
// set.add(applys[a]);
// if (a==applys.length-1 && applys.length != set.size()){
// errorMsg += "适用车型存在重复数据;";
// countError++;
// }
// }
// if (!saveApplyCode.equals("")){
// dto.setApplyArctic(saveApplyCode.substring(0,saveApplyCode.length()-1));
// }
// }
// }
// if(!claimStypelist.contains(dto.getClaimType())) {
// if (StringUtils.isNotEmpty(dto.getClaimType())) {
// dic.setDicTypeName(dto.getClaimType());
// dic.setDicTypeCode("REQUESTTYPE");
// if (dto.getClaimType().length() > 500) {
// errorMsg += "要求类型不能超过500个字符;";
// countError++;
// } else {
// getDic = dicTypeEODao.getDicTypeByDicTypeName(dic);
// Set set = new HashSet();
// if (getDic != null) {
// if (getDic.size() == 1) {
// dto.setClaimType(getDic.get(0).getDicTypeCode());
// claimStypelist.add(getDic.get(0).getDicTypeCode());
// } else if (getDic.size() > 0) {
// errorMsg += "要求类型不明确;";
// countError++;
// } else {
// errorMsg += "要求类型不存在;";
// countError++;
// }
// } else {
// errorMsg += "要求类型不存在;";
// countError++;
// }
// }
// }
// }
if (StringUtils.isEmpty(dto.getMag())) {
errorMsg += "条款内容不能为空;";
countError++;
} else {
if(dto.getMag().length() > 50000){
errorMsg += "条款内容不能超过50000个字符;";
countError++;
}
}
if(!foList.contains(dto.getFo())) {
if (StringUtils.isNotEmpty(dto.getFo())) {
if (dto.getFo().length() > 200) {
errorMsg += "FO不能超过200个字符;";
countError++;
} else {
String uname = roleEODao.getIdsByNames(dto.getFo().split(","));
if (StringUtils.isNotBlank(uname)) {
dto.setFo(uname);
foList.addAll(Arrays.asList(uname.split(",")));
} else {
errorMsg += "FO不存在;";
countError++;
}
}
}
}
if(!dutyEngineerList.contains(dto.getDutyEngineer())) {
if (StringUtils.isNotEmpty(dto.getDutyEngineer())) {
if (dto.getDutyEngineer().length() > 100) {
errorMsg += "责任工程师不能超过100个字符;";
countError++;
} else {
String emList = roleEODao.getIdsByNames(dto.getDutyEngineer().split(","));
if (StringUtils.isNotBlank(emList)) {
dto.setDutyEngineer(emList);
dutyEngineerList.addAll(Arrays.asList(dto.getDutyEngineer().split(",")));
} else {
errorMsg += "系统中没有用户:" + dto.getDutyEngineer();
countError++;
}
}
}
}
if(StringUtils.isNotEmpty(dto.getSvpps())){
if(dto.getSvpps().length() > 200){
errorMsg += "SVPPS不能超过200个字符;";
countError++;
}else {
String svppsShow = sysInfoEOService.getSvppsIdByName(dto.getSvpps());
dto.setSvpps(svppsShow);
}
}
if(StringUtils.isNotEmpty(dto.getBusStandCover())){
if(dto.getBusStandCover().length() > 200){
errorMsg += "企标覆盖关系不能超过200个字符;";
countError++;
}else {
List<DicTypeEO> getDicType = dicTypeEODao.getDicTypeByDicCode("BZFGGXOUIUJ");
for (DicTypeEO dicTypeEO:getDicType) {
if (dicTypeEO.getDicTypeName().equals(dto.getBusStandCover())){
dto.setBusStandCover(dicTypeEO.getDicTypeCode());
}
}
}
}
if(StringUtils.isNotBlank(dto.getResponsibleUnit())){
if(dto.getResponsibleUnit().length() > 100){
errorMsg += "责任部门不能超过100个字符;";
countError++;
}else {
String id = sysInfoEOService.getOrgIdByName(dto.getResponsibleUnit(),"DEPART");
if(StringUtils.isNotBlank(id)){
dto.setResponsibleUnit(id);
} else {
errorMsg += "系统中没有部门"+dto.getResponsibleUnit();
countError++;
}
}
}
// if(!foList.contains(dto.getFo())) {
// if (StringUtils.isNotEmpty(dto.getFo())) {
// if (dto.getFo().length() > 200) {
// errorMsg += "FO不能超过200个字符;";
// countError++;
// } else {
// String uname = roleEODao.getIdsByNames(dto.getFo().split(","));
// if (StringUtils.isNotBlank(uname)) {
// dto.setFo(uname);
// foList.addAll(Arrays.asList(uname.split(",")));
// } else {
// errorMsg += "FO不存在;";
// countError++;
// }
// }
// }
// }
// if(!dutyEngineerList.contains(dto.getDutyEngineer())) {
// if (StringUtils.isNotEmpty(dto.getDutyEngineer())) {
// if (dto.getDutyEngineer().length() > 100) {
// errorMsg += "责任工程师不能超过100个字符;";
// countError++;
// } else {
// String emList = roleEODao.getIdsByNames(dto.getDutyEngineer().split(","));
// if (StringUtils.isNotBlank(emList)) {
// dto.setDutyEngineer(emList);
// dutyEngineerList.addAll(Arrays.asList(dto.getDutyEngineer().split(",")));
// } else {
// errorMsg += "系统中没有用户:" + dto.getDutyEngineer();
// countError++;
// }
// }
// }
// }
// if(StringUtils.isNotEmpty(dto.getSvpps())){
// if(dto.getSvpps().length() > 200){
// errorMsg += "SVPPS不能超过200个字符;";
// countError++;
// }else {
// String svppsShow = sysInfoEOService.getSvppsIdByName(dto.getSvpps());
// dto.setSvpps(svppsShow);
// }
// }
// if(StringUtils.isNotEmpty(dto.getBusStandCover())){
// if(dto.getBusStandCover().length() > 200){
// errorMsg += "企标覆盖关系不能超过200个字符;";
// countError++;
// }else {
// List<DicTypeEO> getDicType = dicTypeEODao.getDicTypeByDicCode("BZFGGXOUIUJ");
// for (DicTypeEO dicTypeEO:getDicType) {
// if (dicTypeEO.getDicTypeName().equals(dto.getBusStandCover())){
// dto.setBusStandCover(dicTypeEO.getDicTypeCode());
// }
// }
// }
// }
// if(StringUtils.isNotBlank(dto.getResponsibleUnit())){
// if(dto.getResponsibleUnit().length() > 100){
// errorMsg += "责任部门不能超过100个字符;";
// countError++;
// }else {
// String id = sysInfoEOService.getOrgIdByName(dto.getResponsibleUnit(),"DEPART");
// if(StringUtils.isNotBlank(id)){
// dto.setResponsibleUnit(id);
// } else {
// errorMsg += "系统中没有部门"+dto.getResponsibleUnit();
// countError++;
// }
// }
// }
if (countError > 0) {
stringMessage.add(errorMsg);
}
@@ -1956,4 +1956,13 @@
</if>
</select>
<!-- 分页查询-->
<select id="queryByPage" resultMap="BaseResultMap"
parameterType="com.adc.da.slrs.sarStandardsInfo.entity.SarStandardsInfoEOPage">
SELECT
<include refid="Base_Column_List_DIS"/>
from SAR_STANDARDS_INFO
limit ${page.pager.startIndex-1},${page.pageSize}
</select>
</mapper>
@@ -0,0 +1,269 @@
package com.adc.da.att.util;
import com.adc.da.util.exception.AdcDaBaseException;
import com.adc.da.util.utils.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;
/**
* @Description
* @Author liyawei
* @Create 2021/7/26
*/
public class CommonExportUtil {
private static final Logger logger = LoggerFactory.getLogger(CommonExportUtil.class);
/**
* 导出excel
* @param columnList 数据库字段名集合
* @param headerList 导出表头集合
* @param datalist
* @param response
* @param request
* @param exportName
* @param tableName
* @throws Exception
*/
public static void exportExcel(List<String> columnList, List<String> headerList, List<Map<String,Object>> datalist, HttpServletResponse response, HttpServletRequest request,
String exportName, String tableName) throws Exception{
final OutputStream os = response.getOutputStream(); // 获得ServletOutputStream对象
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
//response.setHeader("Content-Disposition","attachment; filename=" + URLEncoder.encode(exportName+".xlsx", "UTF-8") + ';');
response.setHeader("Content-Disposition",
"attachment; filename=" + ReadExcel.encodeFileName(exportName+".xlsx", request));
//导出excel
copyrightContractCount(columnList ,headerList ,datalist ,os ,tableName);
}
/**
*
* @param fileName 文件名
* @param headers 表头
* @param desc 填写说明
* @param response
* @param request
* @throws Exception
*/
public static void exportTemplate(String fileName , String[] headers , String desc, HttpServletResponse response, HttpServletRequest request) throws Exception {
// 声明一个工作薄
XSSFWorkbook workbook = new XSSFWorkbook();
// 生成一个表格
XSSFSheet sheet = workbook.createSheet();
//设置表格样式
XSSFCellStyle cellStyle = (XSSFCellStyle) generateCommonCellStyle(workbook,true);
OutputStream os = response.getOutputStream();
try{
// 设置表格默认列宽度为15个字节
//sheet.setDefaultColumnWidth((short) 18);
XSSFRow row = sheet.createRow(0);
for (short i = 0; i < headers.length; i++) {
XSSFCell cell = row.createCell(i);
XSSFRichTextString text = new XSSFRichTextString(headers[i]);
cell.setCellValue(text);
cell.setCellStyle(cellStyle);
}
// 如果填写说明存在,则创建
if (StringUtils.isNotEmpty(desc)){
XSSFRow descRow = sheet.createRow(1);
descRow.setHeightInPoints(80.0F);
XSSFCell descCell = descRow.createCell(0);
descCell.setCellValue(desc);
descCell.setCellStyle(generateDescCellStyle(workbook,true));
CellRangeAddress region = new CellRangeAddress(1, 1,0,headers.length);
sheet.addMergedRegion(region);
}
response.setCharacterEncoding("UTF-8");
// response.setContentType("application/force-download");
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.setHeader("Content-Disposition",
"attachment; filename=" + ReadExcel.encodeFileName(fileName+".xlsx", request));
response.flushBuffer();
workbook.write(os);
} catch (IOException e) {
logger.error("发生异常,异常信息为:"+e.getMessage(), e);
throw new AdcDaBaseException("下载文件失败,请重试");
}finally {
workbook.close();
IOUtils.closeQuietly(os);
}
}
/**
* 导出excel
* @param columnList
* @param headerList
* @param dataList
* @param os
* @param tableName
* @throws Exception
*/
public static void copyrightContractCount(List columnList,List headerList,List dataList ,OutputStream os,String tableName) throws Exception{
try{
Workbook workbook = new XSSFWorkbook();
//产生通用单元格样式
CellStyle style = generateCommonCellStyle(workbook,false);
//创建sheet表单,同时写入标题
CellStyle titleStyle = generateCommonCellStyle(workbook,true);
Sheet sheet = generateSheet(workbook, tableName, columnList, titleStyle);
//写入标题行
writeColumnName(sheet ,headerList ,titleStyle);
//写入数据行
writeDataRow(sheet, columnList, dataList, style);
//输入excel文件
workbook.write(os);
os.close();
//os.flush();
if (workbook != null) {
workbook.close();
}
} catch (IOException e) {
logger.error("发生异常,异常信息为:"+e.getMessage(), e);
throw new AdcDaBaseException("下载文件失败,请重试");
}finally {
IOUtils.closeQuietly(os);
}
}
/**
* 表格导入数据
* @param sheet
* @param columnList
* @param dataList
* @param style
*/
public static void writeDataRow(Sheet sheet, List columnList, List<Map<String,Object>> dataList, CellStyle style){
//columnList 列数
int rowIndex = 2;
for(int i = 0 ; i<dataList.size() ;i++) {
//创建一行
Row dataRow = sheet.createRow(rowIndex++);
//获取该行数据
Map<String,Object> rowDataMap = dataList.get(i);
if (columnList != null && columnList.size() > 0) {
for (int j = 0; j < columnList.size() ;j++) {
//创建单元格
Cell dataCell = dataRow.createCell(j);
//设置单元格样式
dataCell.setCellStyle(style);
//从数据map中获取对应列的数据
if(rowDataMap.get(columnList.get(j)) == null){
continue;
}
String value = String.valueOf(rowDataMap.get(columnList.get(j)));
//将数据写入单元格
dataCell.setCellValue(value);
}
}
}
}
/**
* 第二行设置导出的列名
* @param sheet
* @param headerList
* @param style
*/
public static void writeColumnName(Sheet sheet , List<String> headerList , CellStyle style){
Row titleRow = sheet.createRow(1);
int index = 0;
for(int i = 0;i < headerList.size();i ++){
Cell titleCell = titleRow.createCell(index);
titleCell.setCellStyle(style);
titleCell.setCellValue(headerList.get(i));
index ++;
}
}
/**
* 创建sheet表单,第一行合并单元格设置表格名
* @param workbook
* @param tableName
* @param columnList
* @param style
* @return
*/
public static Sheet generateSheet(Workbook workbook, String tableName, List columnList, CellStyle style){
//创建sheet表单
Sheet sheet = workbook.createSheet(tableName);
//在表单中创建一行
Row tableRow = sheet.createRow(0);
//在行中创建单元格
for(int i = 0;i < columnList.size();i ++){
Cell cell = tableRow.createCell(i);
cell.setCellStyle(style);
}
//获取第一个单元格
Cell tableCell = tableRow.getCell(0);
//给第一个单元格添加数据
tableCell.setCellValue(tableName);
//合并单元格
sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, columnList.size()-1));
return sheet;
}
/**
* 设置单元格样式
* @param workbook
* @return
*/
public static CellStyle generateCommonCellStyle(Workbook workbook, boolean isBold){
//设置表格样式
CellStyle cellStyle = workbook.createCellStyle();
cellStyle.setBorderBottom(BorderStyle.THIN); //下边框
cellStyle.setBorderLeft(BorderStyle.THIN); //左边框
cellStyle.setBorderRight(BorderStyle.THIN); //右边框
cellStyle.setBorderTop(BorderStyle.THIN); //上边框
cellStyle.setAlignment(HorizontalAlignment.CENTER); // 水平居中
cellStyle.setVerticalAlignment(VerticalAlignment.CENTER); // 上下居中
cellStyle.setWrapText(true); // 设置自动换行
Font headerFont = getFont(workbook, (short) 10,isBold); // 创建字体样式
cellStyle.setFont(headerFont); // 为标题样式设置字体样式
return cellStyle;
}
/**
* 设置填写说明样式
* @param workbook
* @return
*/
public static CellStyle generateDescCellStyle(Workbook workbook, boolean isBold){
//设置表格样式
CellStyle cellStyle = workbook.createCellStyle();
cellStyle.setVerticalAlignment(VerticalAlignment.CENTER); // 上下居中
cellStyle.setWrapText(true); // 设置自动换行
Font headerFont = getFont(workbook, (short) 10,isBold); // 创建字体样式
cellStyle.setFont(headerFont); // 为标题样式设置字体样式
return cellStyle;
}
public static Font getFont(Workbook workbook, short size, boolean isBold) {
Font font = workbook.createFont();
font.setFontName("宋体"); // 字体样式
font.setBold(isBold); // 是否加粗
font.setFontHeightInPoints(size); // 字体大小
return font;
}
}
@@ -0,0 +1,175 @@
package com.adc.da.att.util;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
/**
* @des : excel信息读取
* @author: duyunbao
* @email: 1114808306@qq.com
* @date 2017/10/27 17:06
**/
public class ReadExcel {
private static final Logger logger = LoggerFactory.getLogger(ReadExcel.class);
/**
* 总行数
*/
private int totalRows = 0;
/**
* 总条数
*/
private int totalCells = 0;
/**
* 错误信息接收器
*/
private String errorMsg;
public ReadExcel() {
// 不做操作
}
public int getTotalRows() {
return totalRows;
}
public int getTotalCells() {
return totalCells;
}
public String getErrorInfo() {//获取错误信息
return errorMsg;
}
/**
* @method_name: validateExcel
* @des : 验证excel格式
* @author: duyunbao
* @param: [filePath]
* @return: boolean
* @date: 2017/10/27 17:07
**/
public boolean validateExcel(String filePath) {
if (filePath == null || !(WDWUtil.isExcel2003(filePath) || WDWUtil.isExcel2007(filePath))) {
errorMsg = "文件名不是excel格式";
return false;
}
return true;
}
/**
* @method_name: getExcelInfo
* @des : 读EXCEL文件,获取信息集合
* @author: duyunbao
* @param: [fileName, Mfile]
* @return: org.apache.poi.ss.usermodel.Workbook
* @date: 2017/10/27 17:08
**/
public Workbook getExcelInfo(String fileName, MultipartFile Mfile) {
Workbook wb = null;
//把spring文件上传的MultipartFile转换成CommonsMultipartFile类型
CommonsMultipartFile cf = (CommonsMultipartFile) Mfile; //获取本地存储路径
//初始化输入流
InputStream is = null;
try {
//根据文件名判断文件是2003版本还是2007版本
boolean isExcel2003 = true;
if (WDWUtil.isExcel2007(fileName)) {
isExcel2003 = false;
}
is = cf.getInputStream();
//根据excel里面的内容读取客户信息
wb = getExcelInfo(is, isExcel2003, wb);
is.close();
} catch (Exception e) {
logger.error(e.getMessage(),e);
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
is = null;
logger.error(e.getMessage(),e);
}
}
}
return wb;
}
/***
* @method_name: getExcelInfo
* @des : 判断excel版本
* @author: duyunbao
* @param: [is, isExcel2003, wb]
* @return: org.apache.poi.ss.usermodel.Workbook
* @date: 2017/10/27 17:08
**/
private Workbook getExcelInfo(InputStream is, boolean isExcel2003, Workbook wb) {
Workbook workbook =wb;
try {
/** 根据版本选择创建Workbook的方式 */
//当excel是2003时
if (isExcel2003) {
workbook = new HSSFWorkbook(is);
} else {//当excel是2007时
workbook = new XSSFWorkbook(is);
}
} catch (IOException e) {
logger.error(e.getMessage(),e);
}
return workbook;
}
/**
* 获取sheet的名称
* @MethodName:getSheetName
* @author: 马晓晨
* @email: 747052172@qq.com
* @date 2017年11月24日 上午9:49:22
* @version V1.0
* @param filename
* @param file
* @param sheetIndex
* @return
*/
public String getSheetName(String filename, MultipartFile file, Integer sheetIndex) {
Workbook wb = getExcelInfo(filename, file);
return wb.getSheetName(sheetIndex);
}
/**
*
* @Title: encodeFileName
* @Description: 导出文件转换文件名称编码
* @param @param fileNames
* @param @param request
* @param @return 设定文件
* @return String 返回类型
* @throws
*/
public static String encodeFileName(String fileNames , HttpServletRequest request) {
try {
String agent = request.getHeader("User-Agent");
if (agent.contains("Firefox")) {
fileNames = new String(fileNames.getBytes("UTF-8"), "ISO8859-1"); // firefox浏览器
} else {
fileNames = URLEncoder.encode(fileNames, "utf-8");
//谷歌中空格变为+问题
fileNames = fileNames.replaceAll("\\+","%20");
}
} catch (Exception e) {
logger.error(e.getMessage(),e);
}
return fileNames ;
}
}
@@ -0,0 +1,164 @@
package com.adc.da.att.util;
import org.apache.commons.lang3.StringUtils;
import java.util.regex.Pattern;
/**
* @des : excel版本判断类
* @author: duyunbao
* @email: 1114808306@qq.com
* @date 2017/10/27 16:59
**/
public class WDWUtil {
/**
* @method_name: isExcel2003
* @des :是否是2003的excel,返回true是2003
* @author: duyunbao
* @param: [filePath]
* @return: boolean
* @date: 2017/10/27 16:57
**/
public static boolean isExcel2003(String filePath) {
return filePath.matches("^.+\\.(?i)(xls)$");
}
/**
* @method_name: isExcel2007
* @des : 是否是2007的excel,返回true是2007
* @author: duyunbao
* @param: [filePath]
* @return: boolean
* @date: 2017/10/27 16:57
**/
public static boolean isExcel2007(String filePath) {
return filePath.matches("^.+\\.(?i)(xlsx)$");
}
/**
* 判断字符串是否是整数
* @MethodName:isInteger
* @author: DuYunbao
* @date: 2018/5/22 18:00
*/
public static boolean isNumeric(String str){
for (int i = str.length();--i>=0;){
if (!Character.isDigit(str.charAt(i))){
return false;
}
}
return true;
}
/**方法二:推荐,速度最快
* 判断是否为整数
* @param str 传入的字符串
* @return 是整数返回true,否则返回false
*/
public static boolean isInteger(String str) {
Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");
return pattern.matcher(str).matches();
}
/**
* 字母或数字
*
* @MethodName:isLetterDigitOrChinese
* @author: DuYunbao
* @date: 2018/5/30 15:26
*/
public static boolean isLetterOrNumber(String str) {
String regex = "^(\\d|[a-zA-Z])+$";
return !str.matches(regex);
}
/**
* 汉字、字母、()
*
* @MethodName:isLetterOrChineseOrChar1
* @author: DuYunbao
* @date: 2018/5/30 15:53
*/
public static boolean isLetterOrChineseOrChar1(String str) {
String regex = "[^\\a-\\z\\A-\\Z\\u4E00-\\u9FA5\\()\\()]";
return str.matches(regex);
}
/**
* 汉字、字母、数字
*
* @MethodName:isLetterOrChineseOrNumber
* @author: DuYunbao
* @date: 2018/5/30 15:56
*/
public static boolean isLetterOrChineseOrNumber(String str) {
String regex = "^[\\u4E00-\\u9FA5A-Za-z0-9]+$";
return !str.matches(regex);
}
/**
* 汉字、字母、()、-、下划线
*
* @MethodName:isChineseOrLetterOrUnderlineOrChar1
* @author: DuYunbao
* @date: 2018/5/30 16:03
*/
public static boolean isChineseOrLetterOrUnderlineOrChar1(String str) {
String regex = "^[\\u4E00-\\u9FA5A-Za-z_\\-\\()\\()]+$";
return !str.matches(regex);
}
/**
* 数字
*
* @MethodName:isNumbee
* @author: DuYunbao
* @date: 2018/5/30 16:09
*/
public static boolean isNumber(String str) {
String regex = "\\D";
return str.matches(regex);
}
/**
* 数字、大写字母、-
*
* @MethodName:isNumberOrLowerLetterOrChar1
* @author: DuYunbao
* @date: 2018/5/30 16:41
*/
public static boolean isNumberOrLowerLetterOrChar1(String str) {
String regex = "^[A-Z0-9\\-]+$";
return !str.matches(regex);
}
/**
* 汉字、数字、字母、()、-、下划线
*
* @MethodName:isChineseOrNumberOrLetterOrUnderlineOrChar
* @author: DuYunbao
* @date: 2018/5/30 16:45
*/
public static boolean isChineseOrNumberOrLetterOrUnderlineOrChar(String str) {
String regex = "^[\\u4E00-\\u9FA5A-Za-z0-9_\\-\\()\\()]+$";
return !str.matches(regex);
}
/**
* 去除整数含有小数点
* @MethodName:subStr
* @author: DuYunbao
* @date: 2018/5/31 11:19
*/
public static String subStr(String text) {
if (StringUtils.isNotEmpty(text)) {
if(text.contains(".0") && text.substring(text.length()-2,text.length()).equals(".0")) {
text = text.substring(0,text.length()-2);
}
}
return text;
}
}
@@ -88,4 +88,6 @@ public interface DicTypeEODao extends BaseMapper<DicTypeEO> {
String selectByPid(@Param("Info") String Info);
List<DicTypeEO> selectByPidInfo(@Param("pid") String pid);
List<DicTypeEO> selectPidByCode(@Param("fileType") String fileType);
}
@@ -631,4 +631,13 @@
WHERE
DIC_ID = #{pid}
</select>
<select id="selectPidByCode" resultType="com.adc.da.sys.entity.DicTypeEO">
SELECT
*
FROM
ts_dictype
WHERE
DIC_TYPE_CODE = #{fileType}
</select>
</mapper>