使用Ant design vue实现Excel的上传及读取

1、使用组件

 Ant design vue自带上传文件组件,accept限制上传的文件类型

<a-upload
        v-model:file-list="keyList"
        name="file"
        accept=".xlsx,.xls"
        :headers="headers"
        @change="handleKeyChange"
        :customRequest="fileUpload"
      >
        <a-button>
          <upload-outlined></upload-outlined>
          上传
        </a-button>
      </a-upload>

其中action是上传的地址,但是使用action的话,会没有token,项目中出现验证的话就会不可用,这里使用customRequest,它的作用是覆盖默认的上传行为,自定义上传

const fileUpload = function(info){
      console.log(info)

      const formData = new FormData()
      formData.append('file', info.file)
      formData.append('token', 'aiufpaidfupipiu')//随便写一个token示例

      http.request({
        url: "/RedisSyncPlugin/parseExcel",
        method: "post",
        data: formData
      }).then((res) => {
        
        if(res.success){
          info.onSuccess() // 结束上传
          res.data.forEach((item,index) => {
            
            innerValue.value.push({
              srcKey: item[0],
              destKey: item[1],
              id: Date.now() + index,
            });
          });
        }else{
          info.onError() // 结束上传
        }
      })

    }

这里为什么用FormData而不是直接使用info.file,是因为info.file是字符串而不是文件类型,为什么这么用,我也不太清楚,能用就行

出现这样的类型,代表传给后台的是文件

2、后台实现

pom引用


        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>5.2.3</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>5.2.3</version>
        </dependency>

 实现

@ApiOperation(value = "解析excel", notes = "解析excel数据并返回到前端")
    @PostMapping("/parseExcel")
    public JsonResult<?> parseExcel(@RequestParam("file") MultipartFile file) {
        try (InputStream is = new ByteArrayInputStream(file.getBytes())) {
            FileMagic fm = FileMagic.valueOf(is);
            Workbook wb;
            
            if (fm == FileMagic.OOXML) {
                wb = new XSSFWorkbook(is);
            } else {
                wb = new HSSFWorkbook(is);
            }
            
            int activeSheetIdx = wb.getActiveSheetIndex();
            Sheet sheet = wb.getSheetAt(activeSheetIdx);
            
            if (null == sheet) {
                sheet = wb.getSheetAt(0);
            }
            
            List<List<String>> sheetValues = new ArrayList<>();
            
            for (Row row : sheet) {
                List<String> rowValues = new ArrayList<>();
                
                for (Cell cell : row) {
                    String val = cell.getStringCellValue();
                    rowValues.add(val);
                }
                
                sheetValues.add(rowValues);
            }
            
            wb.close();
            
            JsonResult<List<List<String>>> result = new JsonResult<>();
            result.setSuccess(true);
            result.setData(sheetValues);
            return result;
        } catch (Exception e) {
            return JsonResult.ERROR(e.getMessage());
        }
    }

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Ant Design Vue 提供了一个上传组件 `Upload`,通过这个组件可以上传文件到服务器,然后在服务器端读取 Excel 文件里的值。 以下是一个简单的示例: ```vue <template> <div> <a-upload :before-upload="beforeUpload" :on-success="onSuccess" :show-upload-list="false" > <a-button> <a-icon type="upload"></a-icon> 点击上传 </a-button> </a-upload> <div v-if="excelData"> <table> <thead> <tr> <th v-for="header in excelData.headers" :key="header">{{ header }}</th> </tr> </thead> <tbody> <tr v-for="(row, index) in excelData.rows" :key="index"> <td v-for="(cell, cellIndex) in row" :key="cellIndex">{{ cell }}</td> </tr> </tbody> </table> </div> </div> </template> <script> import XLSX from 'xlsx'; export default { data() { return { excelData: null, }; }, methods: { beforeUpload(file) { const isExcel = /xlsx|xls/.test(file.type); if (!isExcel) { this.$message.error('只能上传 Excel 文件!'); } return isExcel; }, onSuccess(response) { const reader = new FileReader(); reader.onload = (event) => { const data = event.target.result; const workbook = XLSX.read(data, { type: 'binary' }); const sheetName = workbook.SheetNames[0]; const worksheet = workbook.Sheets[sheetName]; const excelData = XLSX.utils.sheet_to_json(worksheet, { header: 1 }); this.excelData = { headers: excelData[0], rows: excelData.slice(1) }; }; reader.readAsBinaryString(response.file); }, }, }; </script> ``` 在这个例子中,我们使用 `XLSX` 库来解析 Excel 文件。在上传成功后,我们使用 `FileReader` 对象来读取上传的文件,并将其转换为二进制字符串, 然后使用 `XLSX` 库将其转换为 JSON 数据。最后,我们将这些数据存储在 `excelData` 变量中,以供渲染。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值