当前位置: 首页 > news >正文

Java 用户随机选择导入ZIP文件,解压内部word模板并入库,Windows/可视化Linux系统某麒麟国防系统...均可适配

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 我承认我写的乱七八糟的,但好像就是能入库... 甲方要求这样我就东挪西挪的

http://www.lryc.cn/news/473969.html

相关文章:

  • 【C++】C++17结构化绑定、std::optional、std::variant、std::any
  • C#的起源。J++语言的由来?J#和J++傻傻分不清?
  • Flutter 在 对接 google play 时,利用 android studio 可视化生成 已签名的aab包
  • 使用web.dev提供的工具实现浏览器消息推送服务
  • 计算机系统结构为什么用architecture 而不是structure?
  • sqoop问题汇总记录
  • Git 创建新的分支但清空提交记录
  • SQL PRIMARY KEY
  • 软件测试学习笔记丨Flask操作数据库-对象与数据模型
  • IntelliJ IDEA使用 MybatisX-Generator 插件 自动生成Entity+Mapper+Mapper.xml等代码
  • vue中如何为不同功能设置不同的默认打印设置(设置不同的打印机)
  • 经纬恒润INTEWORK-VBA新版本正式发布
  • 金蝶云数据集成至MySQL的高效解决方案
  • Day02 C++ 环境设置
  • AQS是什么
  • Spring IOC容器简介
  • 【backstopjs】入门安装环境
  • LocalDate 类常用方法详解(日期时间类)
  • kmp desktop实现excel预览
  • OB_GINS_day3
  • 【Python3】【力扣题】405. 数字转换为十六进制数
  • 记录一次企业外部通过ssh 连接数据库的事DBeaver
  • 中聚企服:中聚AI女娲大模型,企业难题迎刃而解!
  • 对镜像精简
  • 老电脑不能装纯净版windows
  • 在Python中实现一个简单的社交媒体应用
  • pytest高版本兼容test_data[“log“] = _handle_ansi(“\n“.join(logs))错误
  • Redis技术入门与实践指南
  • 如何一键完成20个Oracle实例运维脚本部署
  • 【C++刷题】力扣-#598-区间加法 II