使用Ant design vue實(shí)現(xiàn)Excel的上傳及讀取方式
更新時間:2025年04月25日 09:13:26 作者:合肥愛國人士
這篇文章主要介紹了使用Ant design vue實(shí)現(xiàn)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,項(xiàng)目中出現(xiàn)驗(yàn)證的話就會不可用,這里使用customRequest,它的作用是覆蓋默認(rèn)的上傳行為,自定義上傳
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() // 結(jié)束上傳 res.data.forEach((item,index) => { innerValue.value.push({ srcKey: item[0], destKey: item[1], id: Date.now() + index, }); }); }else{ info.onError() // 結(jié)束上傳 } }) }
這里為什么用FormData而不是直接使用info.file,是因?yàn)閕nfo.file是字符串而不是文件類型,為什么這么用,我也不太清楚,能用就行
出現(xiàn)這樣的類型,代表傳給后臺的是文件
2、后臺實(shí)現(xiàn)
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>
實(shí)現(xiàn)
@ApiOperation(value = "解析excel", notes = "解析excel數(shù)據(jù)并返回到前端") @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()); } }
總結(jié)
以上為個人經(jīng)驗(yàn),希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
vue+openlayer5獲取當(dāng)前鼠標(biāo)滑過的坐標(biāo)實(shí)現(xiàn)方法
在vue項(xiàng)目中怎么獲取當(dāng)前鼠標(biāo)劃過的坐標(biāo)呢?下面通過本文給大家分享實(shí)現(xiàn)步驟,感興趣的朋友跟隨小編一起看看吧2021-11-11解決vue-router中的query動態(tài)傳參問題
下面小編就為大家分享一篇解決vue-router中的query動態(tài)傳參問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-03-03