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

java_web接收前端传的excel文件读取数据

#本次做一个将患者数据导入到某个模块的功能,前期集成的代码时不时出现异常,本次进行修改记录

//controller层/*** 导入患者数据*/@RejectReplayRequest@PostMapping("/importData")public Result<?> importData(HttpServletRequest request, LoginUser loginUser, @Param(value = "articleExtDataReq") String articleExtDataReq) throws IOException, ParseException {JSONObject jsonObject = JSONObject.parseObject(articleExtDataReq);String merchantId = jsonObject.getString("articleId");return articleExtDataService.importData(request, loginUser, merchantId);}//service层
/*** 导入更新商品*/Result<?> importData(HttpServletRequest request, LoginUser loginUser, String articleId) throws IOException, ParseException;//impl实现@Overridepublic Result<?> importData(HttpServletRequest request, LoginUser loginUser, String articleId) throws IOException, ParseException {log.info("importData in articleId: " + articleId);//获取厂商信息Article byId = articleService.getById(articleId);if (Objects.isNull(byId)) {return Result.error("您选择的文章不存在");}Map<String, Long> titleAndIdMap = new HashMap<>();Map<Integer, Long> columnIndexAndExtIdMap = new HashMap<>();List<ArticleExt> articleExts = sysArticleExtService.listByArticleId(articleId, loginUser);articleExts.forEach(item -> {titleAndIdMap.put(item.getTitle(), item.getId());});MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {List<ArticleExtData> articleExtDataList = new ArrayList<>();// 获取上传文件对象MultipartFile file = entity.getValue();InputStream inputStream = file.getInputStream();// 创建工作簿对象Workbook workbook = new XSSFWorkbook(inputStream);Date uploadDate = null;// 读取第一个工作表的数据Sheet sheet = workbook.getSheetAt(0);for (Row row : sheet) {int rowNum = row.getRowNum();Iterator<Cell> cellIterator = row.cellIterator();JSONObject jsonObject = new JSONObject();while (cellIterator.hasNext()) {Cell cell = cellIterator.next();cell.setCellType(CellType.STRING);int columnIndex = cell.getColumnIndex();// 处理单元格数据,这里只是简单地打印出来String stringCellValue = cell.getStringCellValue();
//                    System.out.print(rowNum + "  " + columnIndex + "  " + stringCellValue + "\t");if (rowNum == 0) {Long ExtId = titleAndIdMap.get(stringCellValue);if (ExtId == null && !stringCellValue.contains("时间")) {//判断excel标题是否存在于系统return Result.error("系统不存在【" + stringCellValue + "】参数,请在扩展数据中添加该参数信息");}if (ExtId != null) {columnIndexAndExtIdMap.put(columnIndex, ExtId);}} else {if (rowNum == 1 && columnIndex == 5 && stringCellValue.length() == 5) {stringCellValue = DateUtils.ExcelDoubleToDate(stringCellValue);uploadDate = DateUtils.parseDate(stringCellValue, "yyyy-MM-dd");}if (columnIndex != 5) {jsonObject.put(String.valueOf(columnIndexAndExtIdMap.get(columnIndex)), stringCellValue);}}}ArticleExtData articleExtData = new ArticleExtData();articleExtData.setArticleId(articleId).setCreatedBy(loginUser.getId()).setUpdatedBy(loginUser.getId()).setValue(jsonObject.toJSONString()).setCreatedTime(uploadDate).setUpdatedTime(uploadDate);articleExtDataList.add(articleExtData);
//                System.err.println(jsonObject);}articleExtDataService.saveBatch(articleExtDataList);}return Result.OK("导入完成");}

前端代码

//html
<el-uploadclass="upload-demo"action="#":show-file-list="false":on-change="importData":auto-upload="false"accept=".xlsx, .xls"style="display: inline; margin-right: 10px"><el-button type="primary" icon="el-icon-download">导入</el-button></el-upload><el-button type="text" @click="downTemplate()">下载导入模板</el-button>//jsimport axios from "axios";importData(param) {const that = this;showLoading(); //显示加载中let formData = new FormData(); //声明一个FormDate对象formData.append("file", param.raw); //把文件信息放入对象中formData.append("articleExtDataReq",JSON.stringify(this.articleExtDataObj.formData));this.path = localStorage.getItem("urlcode");let text = `${this.path}/articleExtData/importData`;axios({url: text,method: "post",async: false,processData: false,contentType: false, // 不设置数据类型data: formData,headers: {"X-Access-Token": sessionStorage.getItem("token")}}).then(res => {if (res.data.success == true) {that.$message({type: "success",message: res.data.message});setTimeout(() => {that.getlist();}, 600);} else {that.$message.error(res.data.message);}}).catch(err => {that.$message({type: "error",message: "导入失败"});});setTimeout(() => {hideLoading();}, 1200);},// 下载导入模板downTemplate() {window.open("https://qiniu.sjhlwyy.com/ExcelTemp/Free_consultation_activities_Patient_data.xlsx");},

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

相关文章:

  • 在Vue开发中v-if指令和v-show指令的使用介绍和区别及使用场景
  • Power Query是啥
  • 在k8s中部署nfs-client-provisioner
  • 23.12.10日总结
  • 持续集成交付CICD:通过API方式上传Nexus制品
  • Hadoop学习笔记(HDP)-Part.14 安装YARN+MR
  • reinforce 跑 CartPole-v1
  • 【VRTK】【VR开发】【Unity】13-攀爬
  • 华为OD机试真题-求幸存数之和-2023年OD统一考试(C卷)
  • python pyaudio实时读取音频数据并展示波形图
  • 【算法系列篇】递归、搜索和回溯(二)
  • Ubuntu下安装SDL
  • 创建vue项目:vue脚手架安装、vue-cli安装,vue ui界面创建vue工程(vue2/vue3),安装vue、搭建vue项目开发环境(保姆级教程二)
  • 【3】密评-物理和环境安全测评
  • 笨爸爸工房,我们在校园|“小鲁班”,铸未来
  • RPC 集群,gRPC 广播和组播
  • OpenSSL SSL_read: Connection was reset, errno 10054
  • 【springboot】整合redis和定制化
  • HarmonyOS鸿蒙操作系统架构开发
  • 共创共赢|美创科技获江苏移动2023DICT生态合作“产品共创奖”
  • 深度学习——第3章 Python程序设计语言(3.5 Python类和对象)
  • 【原创】【一类问题的通法】【真题+李6卷6+李4卷4(+李6卷5)分析】合同矩阵A B有PTAP=B,求可逆阵P的策略
  • 代码随想录算法训练营第六十天 | 84.柱状图中最大的矩形
  • C#结合JavaScript实现多文件上传
  • STM32——继电器
  • 性能监控体系:InfluxDB Grafana Prometheus
  • CS106L2023 and CS106B 环境配置(详细教程)
  • Docker-多容器应用
  • Golang导入导出Excel表格
  • 基于Maven的Spring Boot应用版本号获取解析