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实现


    @Override
    public 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-upload
              class="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>


//js

import 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"
      );
    },

  • 8
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一丝净土

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值