fix: 修复导入模板时按照上传解密后的文件进行解析

This commit is contained in:
zhangyanduan
2022-10-08 13:54:05 +08:00
parent 8a77f17b43
commit 36c94e2aaf
4 changed files with 214 additions and 70 deletions
@@ -68,9 +68,9 @@ public class exportWkExcel {
@ApiOperation(value = "|SarFileSplitItemsEO|导入") @ApiOperation(value = "|SarFileSplitItemsEO|导入")
@PostMapping(value = "/importData") @PostMapping(value = "/importData")
public ResponseMessage<?> importSplitItemsZip(@RequestParam(value = "file", required = false) MultipartFile file) throws Exception { public ResponseMessage<?> importSplitItemsZip(@RequestParam(value = "importFileId", required = false) String importFileId) throws Exception {
StringBuilder stringBuilder=new StringBuilder(); StringBuilder stringBuilder=new StringBuilder();
List<importExcelDTO> res=exportService.delWithWkData(file,stringBuilder); List<importExcelDTO> res=exportService.delWithWkData(importFileId,stringBuilder);
if(null==res){ if(null==res){
return Result.error("-1","","请严格按照模板上传文件"); return Result.error("-1","","请严格按照模板上传文件");
}else if (stringBuilder.toString().length()>0){ }else if (stringBuilder.toString().length()>0){
@@ -7,6 +7,6 @@ import java.util.List;
public interface IExportService { public interface IExportService {
List<importExcelDTO> delWithWkData(MultipartFile file ,StringBuilder stringBuilder) throws Exception; List<importExcelDTO> delWithWkData(String importFileId ,StringBuilder stringBuilder) throws Exception;
} }
@@ -1,5 +1,7 @@
package com.adc.da.slrs.processModel.service.impl; package com.adc.da.slrs.processModel.service.impl;
import com.adc.da.att.entity.AttFileEO;
import com.adc.da.att.service.IAttFileEOService;
import com.adc.da.slrs.processModel.entity.importExcelDTO; import com.adc.da.slrs.processModel.entity.importExcelDTO;
import com.adc.da.slrs.processModel.service.IExportService; import com.adc.da.slrs.processModel.service.IExportService;
import com.adc.da.slrs.processModel.utils.DateUtil; import com.adc.da.slrs.processModel.utils.DateUtil;
@@ -15,9 +17,11 @@ import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.poi.hssf.usermodel.HSSFDateUtil; import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.text.DateFormat; import java.text.DateFormat;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.*; import java.util.*;
@@ -38,87 +42,108 @@ public class IExportServiceImpl implements IExportService {
private TsUserServiceImpl tsUserService; private TsUserServiceImpl tsUserService;
@Autowired
private IAttFileEOService attFileEOService;
@Value("${file.path}")
private String filePath;//文件存储路径
@Override @Override
public List<importExcelDTO> delWithWkData(MultipartFile file ,StringBuilder stringBuilder) throws Exception { public List<importExcelDTO> delWithWkData(String importFileId ,StringBuilder stringBuilder) throws Exception {
// //获取数据字典数据 AttFileEO fileInfo = attFileEOService.getFileInfo(importFileId);
if(fileInfo!=null){
//文件
String importFilePath = filePath+fileInfo.getFilePath()+fileInfo.getFileName();
File importFile = new File(importFilePath);
if(!importFile.exists()){
return null;
}
// //获取数据字典数据
// Map<String, Object> dicTypeEO = dicTypeEOService.getDicTypeListCode(); // Map<String, Object> dicTypeEO = dicTypeEOService.getDicTypeListCode();
//获取机构数据 //获取机构数据
QueryWrapper<TsInstitution> wrapper=new QueryWrapper<>(); QueryWrapper<TsInstitution> wrapper=new QueryWrapper<>();
wrapper.select("id","name"); wrapper.select("id","name");
List<TsInstitution> tsInstitutions=tsInstitutionService.list(wrapper); List<TsInstitution> tsInstitutions=tsInstitutionService.list(wrapper);
//获取人员数据 //获取人员数据
QueryWrapper<TsUser> tsUserQueryWrapper=new QueryWrapper<>(); QueryWrapper<TsUser> tsUserQueryWrapper=new QueryWrapper<>();
tsUserQueryWrapper.select("ACCOUNT","UNAME"); tsUserQueryWrapper.select("ACCOUNT","UNAME");
tsUserQueryWrapper.eq("VALID_FLAG","0"); tsUserQueryWrapper.eq("VALID_FLAG","0");
List<TsUser> tsUsers=tsUserService.list(tsUserQueryWrapper); List<TsUser> tsUsers=tsUserService.list(tsUserQueryWrapper);
//获取institution工具集合 //获取institution工具集合
Map<String,String> tsInstitutionMap=new HashMap<>(); Map<String,String> tsInstitutionMap=new HashMap<>();
tsInstitutions.forEach(tsInstitution -> { tsInstitutions.forEach(tsInstitution -> {
tsInstitutionMap.put(tsInstitution.getName(),tsInstitution.getId()); tsInstitutionMap.put(tsInstitution.getName(),tsInstitution.getId());
}); });
//获取user工具集合 //获取user工具集合
Map<String,String> tsUserMap=new HashMap<>(); Map<String,String> tsUserMap=new HashMap<>();
tsUsers.forEach(tsUser -> { tsUsers.forEach(tsUser -> {
tsUserMap.put(tsUser.getAccount(),tsUser.getUname()); tsUserMap.put(tsUser.getAccount(),tsUser.getUname());
}); });
List<importExcelDTO> res= ExcelImportUtilByWk.readExcelpublic(importExcelDTO.class,file,stringBuilder); List<importExcelDTO> res= ExcelImportUtilByWk.readExcelpublic(importExcelDTO.class,importFile,stringBuilder);
if (null!=res) { if (null!=res) {
DateFormat formater = new SimpleDateFormat("yyyy-MM-dd"); DateFormat formater = new SimpleDateFormat("yyyy-MM-dd");
int i = 1; int i = 1;
for (importExcelDTO importExcelDTO : res) { for (importExcelDTO importExcelDTO : res) {
if (null != importExcelDTO.getWgLeader() && !"".equals(importExcelDTO.getWgLeader())) { if (null != importExcelDTO.getWgLeader() && !"".equals(importExcelDTO.getWgLeader())) {
importExcelDTO.setWgLeaderName(tsUserMap.get(importExcelDTO.getWgLeader())+"("+importExcelDTO.getWgLeader()+")"); importExcelDTO.setWgLeaderName(tsUserMap.get(importExcelDTO.getWgLeader())+"("+importExcelDTO.getWgLeader()+")");
if (null == tsUserMap.get(importExcelDTO.getWgLeader())) { if (null == tsUserMap.get(importExcelDTO.getWgLeader())) {
stringBuilder.append("" + i + "行第7列工作组组长填写不符合格式要求请检查;"); stringBuilder.append("" + i + "行第7列工作组组长填写不符合格式要求请检查;");
}
} }
} if (null != importExcelDTO.getUnitName() && !"".equals(importExcelDTO.getUnitName())) {
if (null != importExcelDTO.getUnitName() && !"".equals(importExcelDTO.getUnitName())) { importExcelDTO.setUnit(tsInstitutionMap.get(importExcelDTO.getUnitName()));
importExcelDTO.setUnit(tsInstitutionMap.get(importExcelDTO.getUnitName())); if (null == tsInstitutionMap.get(importExcelDTO.getUnitName())) {
if (null == tsInstitutionMap.get(importExcelDTO.getUnitName())) { stringBuilder.append("" + i + "行第4列起草责任单位填写不符合格式要求请检查;");
stringBuilder.append("" + i + "行第4列起草责任单位填写不符合格式要求请检查;"); }
} }
} if (null != importExcelDTO.getDrafter() && !"".equals(importExcelDTO.getDrafter())) {
if (null != importExcelDTO.getDrafter() && !"".equals(importExcelDTO.getDrafter())) { importExcelDTO.setDrafterName(tsUserMap.get(importExcelDTO.getDrafter())+"("+importExcelDTO.getDrafter()+")");
importExcelDTO.setDrafterName(tsUserMap.get(importExcelDTO.getDrafter())+"("+importExcelDTO.getDrafter()+")"); if (null == tsUserMap.get(importExcelDTO.getDrafter())) {
if (null == tsUserMap.get(importExcelDTO.getDrafter())) { stringBuilder.append("" + i + "行第5列起草人填写不符合格式要求请检查;");
stringBuilder.append("" + i + "行第5列起草人填写不符合格式要求请检查;"); }
} }
} if (null != importExcelDTO.getResPerson() && !"".equals(importExcelDTO.getResPerson())) {
if (null != importExcelDTO.getResPerson() && !"".equals(importExcelDTO.getResPerson())) { importExcelDTO.setResPersonName(tsUserMap.get(importExcelDTO.getResPerson())+"("+importExcelDTO.getResPerson()+")");
importExcelDTO.setResPersonName(tsUserMap.get(importExcelDTO.getResPerson())+"("+importExcelDTO.getResPerson()+")"); if (null == tsUserMap.get(importExcelDTO.getResPerson())) {
if (null == tsUserMap.get(importExcelDTO.getResPerson())) { stringBuilder.append("" + i + "行第6列评审责任人填写不符合格式要求请检查;");
stringBuilder.append("" + i + "行第6列评审责任人填写不符合格式要求请检查;"); }
} }
} try {
try { if (null != importExcelDTO.getEndTime() && !"".equals(importExcelDTO.getEndTime())) {
if (null != importExcelDTO.getEndTime() && !"".equals(importExcelDTO.getEndTime())) { importExcelDTO.setEndTime(formater.format(HSSFDateUtil.getJavaDate(Double.valueOf(importExcelDTO.getEndTime()))));
importExcelDTO.setEndTime(formater.format(HSSFDateUtil.getJavaDate(Double.valueOf(importExcelDTO.getEndTime())))); }
} catch (Exception e) {
stringBuilder.append("" + i + "行第10列立项完成时间填写不符合格式要求请检查;");
} }
} catch (Exception e) { try {
stringBuilder.append("" + i + "行第10列立项完成时间填写不符合格式要求请检查;"); if (null != importExcelDTO.getReleaseTime() && !"".equals(importExcelDTO.getReleaseTime())) {
} importExcelDTO.setReleaseTime(formater.format(HSSFDateUtil.getJavaDate(Double.valueOf(importExcelDTO.getReleaseTime()))));
try { }
if (null != importExcelDTO.getReleaseTime() && !"".equals(importExcelDTO.getReleaseTime())) { } catch (Exception e) {
importExcelDTO.setReleaseTime(formater.format(HSSFDateUtil.getJavaDate(Double.valueOf(importExcelDTO.getReleaseTime())))); stringBuilder.append("" + i + "行第9列计划标准发布时间填写不符合格式要求请检查;");
} }
} catch (Exception e) { try {
stringBuilder.append("" + i + "行第9列计划标准发布时间填写不符合格式要求请检查;"); if (null != importExcelDTO.getDraftTime() && !"".equals(importExcelDTO.getDraftTime())) {
} importExcelDTO.setDraftTime(formater.format(HSSFDateUtil.getJavaDate(Double.valueOf(importExcelDTO.getDraftTime()))));
try { }
if (null != importExcelDTO.getDraftTime() && !"".equals(importExcelDTO.getDraftTime())) { } catch (Exception e) {
importExcelDTO.setDraftTime(formater.format(HSSFDateUtil.getJavaDate(Double.valueOf(importExcelDTO.getDraftTime())))); stringBuilder.append("" + i + "行第8列计划初稿完成日期填写不符合格式要求请检查;");
} }
} catch (Exception e) { i++;
stringBuilder.append("" + i + "行第8列计划初稿完成日期填写不符合格式要求请检查;");
} }
i++;
return res;
}else {
return null;
} }
}else{
return res;
}else {
return null; return null;
} }
} }
} }
@@ -15,6 +15,8 @@ import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.lang.reflect.Field; import java.lang.reflect.Field;
@@ -146,6 +148,123 @@ public class ExcelImportUtilByWk {
} }
} }
/**
* 读取Excel文件内容
* @param file 上传的Excel文件
* @return 读取结果列表,读取失败时返回null
*/
public static <T> List<T> readExcelpublic(Class<T> tClass, File file, StringBuilder stringBuilder) {
Workbook workbook = null;
InputStream is = null;
try {
// 获取Excel后缀名
String fileName = file.getName();
if (fileName == null || fileName.isEmpty() || fileName.lastIndexOf(".") < 0) {
log.warn("解析Excel失败,因为获取到的Excel文件名非法!");
return null;
}
String fileType = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
is = new FileInputStream(file);
// 获取Excel工作簿
workbook = getWorkbook(is, fileType);
//不同需求条件下可以 在此处修改 来获取不同的对象
List<T> resultDataList = new ArrayList<>();
// 解析sheet
for (int sheetNum = 0; sheetNum < workbook.getNumberOfSheets(); sheetNum++) {
Sheet sheet = workbook.getSheetAt(sheetNum);
if(!"hidden".equals(sheet.getSheetName())) {
// 校验sheet是否合法
if (sheet == null) {
continue;
}
// 获取第一行数据
int firstRowNum = sheet.getFirstRowNum();
Row firstRow = sheet.getRow(firstRowNum);
if (null == firstRow) {
log.warn("解析Excel失败,在第一行没有读取到任何数据!");
}
// 解析每一行的数据,构造数据对象
int rowStart = firstRowNum + 1;
int rowEnd = sheet.getPhysicalNumberOfRows();
Map<Integer,Field> map=new HashMap<>();
Map<Integer,Excel> mapExcel=new HashMap<>();
Field[] fields=tClass.getDeclaredFields();
for (Field field:fields) {
field.setAccessible(true);
Excel excel=field.getAnnotation(Excel.class);
if (null!=excel) {
map.put(Integer.valueOf(excel.orderNum()), field);
mapExcel.put(Integer.valueOf(excel.orderNum()), excel);
}
}
Row headRow=sheet.getRow(firstRowNum);
for (int j=0;j<mapExcel.keySet().size();j++){
if (!headRow.getCell(j).toString().equals(mapExcel.get(j).name())){
//返回null就是表头没对上 excel错误
return null;
}
}
for (int rowNum = rowStart; rowNum < rowEnd; rowNum++) {
T o = tClass.getConstructor(new Class[]{}).newInstance(new Object[]{});
int nums=0;
Row row = sheet.getRow(rowNum);
if (null == row) {
continue;
}
for (Integer a:map.keySet()) {
Cell cell=null;
cell = row.getCell(a);
if (null!=mapExcel.get(a).exportFormat() && !"".equals(mapExcel.get(a).exportFormat())) {
String value = convertCellValueToString(cell);
Date date= DateUtils.stringToDate(TrainFormDate.dealWithTimeZoneyyyy(value,mapExcel.get(a).exportFormat()),mapExcel.get(a).exportFormat());
// Date date= DateUtils.stringToDate(value,mapExcel.get(a).exportFormat());
if (null!=value && !"".equals(value) && null==date){
stringBuilder.append(""+rowNum+"行第"+a+"列,日期格式存在问题请检查;");
}
if (null==date && null!=value){
nums++;
}
map.get(a).set(o, date);
}else {
String value = convertCellValueToString(cell);
if (StringUtils.isBlank(value)){
value="";
}
map.get(a).set(o, value);
}
}
if (nums==0) {
resultDataList.add(o);
}
}
}
}
return resultDataList;
} catch (Exception e) {
log.warn("解析Excel失败,文件名:" + file.getName() + " 错误信息:" + e.getMessage());
return null;
} finally {
try {
if (null != workbook) {
workbook.close();
}
if(is!=null){
is.close();
}
} catch (Exception e) {
log.warn("关闭数据流出错!错误信息:" + e.getMessage());
return null;
}
}
}
/** /**
* 根据文件后缀名类型获取对应的工作簿对象 * 根据文件后缀名类型获取对应的工作簿对象
* @param inputStream 读取文件的输入流 * @param inputStream 读取文件的输入流