1.效果
压缩包内部文件
2.依赖
<!--支持Zip--><dependency><groupId>net.lingala.zip4j</groupId><artifactId>zip4j</artifactId><version>2.11.5</version></dependency>总之是要File类变MultipartFile类型的 好像是下面这仨个 你们都添加进去吧<!--file类型转换Mu...--><dependency><groupId>org.springframework</groupId><artifactId>spring-web</artifactId><version>5.2.13.RELEASE</version></dependency><dependency><groupId>commons-fileupload</groupId><artifactId>commons-fileupload</artifactId><version>1.3.1</version></dependency><!--file类型转换Mu...--><dependency><groupId>org.springframework</groupId><artifactId>spring-test</artifactId></dependency>
3.Impl 代码
@Override
public Result importFileA(MultipartFile multipartFile,Integer modelMarking) throws IOException {//创建临时目录用于解压//ChatGPT解释// --> Linux/macOS:通常在/tmp目录下。例如/temp/uploadZip_XXXXXX.// --> Windows:通常在 C:\Users\<用户名>\AppData\Local\Temp 目录下,例如 C:\Users\<用户名>\AppData\Local\Temp\uploadZip_XXXXXX.Path uploadZip = Files.createTempDirectory("uploadZip_");File directory = new File(uploadZip.toString());if (!directory.exists()){directory.mkdir();}//zip文件目录String zipFilePath = uploadZip + "/" + multipartFile.getOriginalFilename();//自定义文件写入临时项目目录中try{multipartFile.transferTo(new File(zipFilePath));}catch (Exception e){e.printStackTrace();}//解压ZIP文件List<String> s = unzipAndPrintPaths(zipFilePath, uploadZip.toString());for (String string : s) {File file = new File(string);//将文件写入指定路径MultipartFile cMultiFile = new MockMultipartFile("file", file.getName(), null, new FileInputStream(file));if (modelMarking == 1) {importFileAF1(cMultiFile);} else if (modelMarking == 2) {importFileAF2(cMultiFile);} else if (modelMarking == 3) {importFileAF3(cMultiFile);}}//清除临时文档Files.walk(uploadZip).sorted((a,b)->b.compareTo(a)).forEach(f -> f.toFile().delete());}return Result.success();}
3.1 挑一个importFileAF1这个方法解读
public void importFileAF1(MultipartFile multipartFile) throws IOException {InputStream inputStream = null;File file = null;try{// 创建临时文件file = File.createTempFile("temp", null);// 把multipartFile写入临时文件multipartFile.transferTo(file);// 使用文件创建 inputStream 流inputStream = new FileInputStream(file);//读取Word文档XWPFDocument document = new XWPFDocument(inputStream);//保存报表A数据TestRecord testRecord = new TestRecord();//头标签String handTab = null;String fileName = null;// 遍历头表头// 遍历文档的每个段落for (XWPFParagraph paragraph : document.getParagraphs()) {String content = paragraph.getText();if(content.startsWith("F1")){testRecord.setModelId(1);} else if (content.startsWith("F2")) {testRecord.setModelId(2);} else if (content.startsWith("F3")) {testRecord.setModelId(3);}if (content.startsWith("文件名:")){String[] parts = content.split(":", 2);fileName = parts[1];//set名字时待整改testRecord.setFileName(parts[1]);String part = parts[1];String[] split = part.split("_", 6);handTab = split[3];}}List<StringBuffer> joinList = new ArrayList<>();// 识别下方// 获取文档中的所有表格List<XWPFTable> tables = document.getTables();// 遍历每个表格for (XWPFTable table : tables) {// 获取表格的行List<XWPFTableRow> rows = table.getRows();// 遍历每一行for (XWPFTableRow row : rows) {// 获取行中的单元格List<XWPFTableCell> cells = row.getTableCells();StringBuffer stringBuffer = new StringBuffer();// 遍历每个单元格for (XWPFTableCell cell : cells) {// 输出单元格的文本内容System.out.print(cell.getText() + "|");stringBuffer.append(cell.getText() + "|");}joinList.add(stringBuffer);System.out.println(); // 换行}System.out.println(); // 表格间换行}JSONObject jsonObject = new JSONObject();JSONArray checkItems = new JSONArray();/*** vehicle_info* 需要 unit_id √* 需要 powerHours √* 需要 powerPackWorking √* 需要 powerPackYieldHours √* 需要 taskPayloadWorkingHours √* 需要 factoryDate √* 需要 plateNumber √*///拼凑vehicle_info数据JSONObject vehicleInfo = new JSONObject();String[] split;//采集子数据List<String> sonList = new ArrayList<>();for(StringBuffer sb:joinList){//特殊处理if (sb.toString().equals("|")){continue;}if (sb.toString().startsWith("装备基础信息")){split = sb.toString().split("\\|");testRecord.setModelName(split[2]);vehicleInfo.put("powerHours",split[4]);continue;//testRecord} else if (sb.toString().startsWith("|车辆编号")) {split = sb.toString().split("\\|");testRecord.setPlateNum(split[2]);vehicleInfo.put("plateNumber",split[2]);vehicleInfo.put("powerPackWorkingHours",split[4]);//接收null值continue;} else if (sb.toString().startsWith("|所属机构")) {split = sb.toString().split("\\|");//if (split[2].contains("/")){String[] split1 = split[2].split("/");Unit unit1 = unitMapper.selectOne(new QueryWrapper<Unit>().lambda().eq(Unit::getUnitName, split1[1]));if(unit1.getUnitName()!=null){vehicleInfo.put("unitId",unit1.getUnitId());}}else {Unit unit1 = unitMapper.selectOne(new QueryWrapper<Unit>().lambda().eq(Unit::getUnitName,split[2]));if (unit1.getUnitName()!=null){vehicleInfo.put("unitId",unit1.getUnitId());}}vehicleInfo.put("powerPackYieldHours",Optional.ofNullable(split[4]).orElse("0"));continue;} else if (sb.toString().startsWith("|出厂日期")) {split = sb.toString().split("\\|");vehicleInfo.put("factoryDate",split[2]);vehicleInfo.put("taskPayloadWorkingHours",Optional.ofNullable(split[4]).orElse("0"));continue;} else if (sb.toString().startsWith("|车辆里程数(km)")){split = sb.toString().split("\\|");try {testRecord.setMileage(Double.parseDouble(split[2]));vehicleInfo.put("mileage",split[2]);testRecord.setCreateTime(split[4]);} catch (NumberFormatException e) {e.printStackTrace();}continue;} else if (sb.toString().startsWith("|||备注|")){split = sb.toString().split("\\|");try {testRecord.setRemark(split[4]);} catch (NumberFormatException e) {e.printStackTrace();}continue;} else if (sb.toString().startsWith("序号|")) {continue;}sonList.add(sb.toString());}String[] split2 = fileName.split("_");//组装数据JSONObject returnResult = new JSONObject();returnResult.put("topSystem",false);returnResult.put("systemName",split2[3]);JSONArray objects = new JSONArray();//解锁遍历for(String entity:sonList){String[] split1 = entity.toString().split("\\|");JSONObject Json = new JSONObject();if(split1[1].split(" ")[0].contains("感知故障码") || split1[1].split(" ")[0].contains("感知提示码") || split1[1].split(" ")[0].contains("平台故障码") || split1[1].split(" ")[0].contains("平台提示码")){Json.put("code",split1[1].split(" ")[1]);Json.put("name",split1[2]);//判断红绿状态if ("故障".equals(split1[5])){Json.put("state",false);Json.put("stateMessage","故障");}else {Json.put("state",true);Json.put("stateMessage","提示");}}else{Json.put("name",split1[1]);Json.put("stateMessage",split1[2]);//判断红绿状态if ("故障".equals(split1[5])){Json.put("state",false);}else {Json.put("state",true);}}objects.add(Json);}returnResult.put("checkItems",objects);testRecord.setDetail("["+JSONObject.toJSONString(returnResult,SerializerFeature.WriteMapNullValue)+"]");testRecord.setContent(split2[3]);testRecord.setUnitId(Integer.valueOf(vehicleInfo.get("unitId").toString()));testRecord.setVehicleInfo(JSONObject.toJSONString(vehicleInfo, SerializerFeature.WriteMapNullValue));testRecordMapper.insert(testRecord);}catch (Exception e){e.printStackTrace();//关闭文件流inputStream.close();}finally {// 最后记得删除文件file.deleteOnExit();// 关闭流inputStream.close();}}
3.2 我承认我写的乱七八糟的,但好像就是能入库... 甲方要求这样我就东挪西挪的