Vue結(jié)合后臺導入導出Excel問題詳解
最近Vue項目中用到了導入導出功能,在網(wǎng)上搜索了一番之后,決定采用Blob方式,這也是大家推薦的一種的方式,特此做下記錄。
導出Excel功能
這里不談別人怎么實現(xiàn)的,我是從后臺生成了Excel流文件返回給前端的。
下面具體看一下后臺的代碼:
/** * 批量導出用戶 * @param condition * @param response */ @PostMapping("/exportUser") public void exportUser(@RequestBody UserQueryCondition condition,HttpServletResponse response){ XSSFWorkbook book = new XSSFWorkbook(); try { List<UserParam> list = indexService.exportUser(condition); if (list != null && list.size() > 0) { XSSFSheet sheet = book.createSheet("mySheent"); String[] vals = {"用戶ID", "郵箱賬號","昵稱","年齡","性別","狀態(tài)", "注冊時間"}; createExcel(sheet, 0, vals); for (int i = 0; i < list.size(); i++) { UserParam entity = list.get(i); String[] vals2 = new String[]{String.valueOf(entity.getId()), entity.getEmail(), entity.getName(), String.valueOf(entity.getAge()), entity.getSex() == 0 ? "女":"男",entity.getRemoved() == 0 ? "啟用":"禁用",entity.getRegisterDate()}; createExcel(sheet, i + 1, vals2); } book.write(generateResponseExcel("用戶列表",response)); } book.close(); }catch(Exception e){ e.printStackTrace(); } }
/** * @param excelName * 要生成的文件名字 * @return * @throws IOException */ private ServletOutputStream generateResponseExcel(String excelName, HttpServletResponse response) throws IOException { excelName = excelName == null || "".equals(excelName) ? "excel" : URLEncoder.encode(excelName, "UTF-8"); response.setContentType("application/vnd.ms-excel;charset=utf-8"); response.setHeader("Content-Disposition", "attachment; filename=" + excelName + ".xlsx"); return response.getOutputStream(); }
對于第一個函數(shù)exportUser
來說,主要是根據(jù)傳回來的條件查詢數(shù)據(jù)庫并生成相應(yīng)的Excel表格,之后book.write(generateResponseExcel(“用戶列表”,response)); 這行代碼調(diào)用第二個函數(shù)generateResponseExcel
來生成流文件以及處理返回的Response。
這里需要注意的地方就兩個:
response.setContentType("application/vnd.ms-excel;charset=utf-8"); response.setHeader("Content-Disposition", "attachment; filename=" + excelName + ".xlsx");
第一行application/vnd.ms-excel說明將結(jié)果導出為Excel
第二行說明提供那個打開/保存對話框,將文件作為附件下載
上面就是后臺的全部代碼了,接下來看一下前端的代碼:
axios({ method: 'post', url: 'http://localhost:19090/exportUser', data: { email: this.email, userIdArray: this.userIdArray, startRegisterDate: this.registerStartTime, endRegisterDate: this.registerEndTime }, responseType: 'blob' }).then((res) => { console.log(res) const link = document.createElement('a') let blob = new Blob([res.data],{type: 'application/vnd.ms-excel'}); link.style.display = 'none' link.href = URL.createObjectURL(blob); let num = '' for(let i=0;i < 10;i++){ num += Math.ceil(Math.random() * 10) } link.setAttribute('download', '用戶_' + num + '.xlsx') document.body.appendChild(link) link.click() document.body.removeChild(link) }).catch(error => { this.$Notice.error({ title: '錯誤', desc: '網(wǎng)絡(luò)連接錯誤' }) console.log(error) })
這里為了方便做記錄,我是直接在頁面中使用axios發(fā)送了個post請求。
仔細看axios請求加了個responseType: 'blob'
配置,這是很重要的
可以看一下請求成功之后返回的數(shù)據(jù):
可以看到請求返回了一個Blob對象,你如果沒有正確的加上responseType: 'blob'這個參數(shù),返回的就不是個Blob對象,而是字符串了。
接下來就是將返回的Blob對象下載下來了:
const link = document.createElement('a') let blob = new Blob([res.data],{type: 'application/vnd.ms-excel'}); link.style.display = 'none' link.href = URL.createObjectURL(blob); let num = '' for(let i=0;i < 10;i++){ num += Math.ceil(Math.random() * 10) } link.setAttribute('download', '用戶_' + num + '.xlsx') document.body.appendChild(link) link.click() document.body.removeChild(link)
上面這段代碼重要的就一句:let blob = new Blob([res.data],{type: ‘a(chǎn)pplication/vnd.ms-excel'});
其余的看看就行了。
以上就是全部的Vue導出Excel前后端代碼了。
導入Excel功能
其實對于這個導入Excel沒有什么好說的,就和你沒采用前后分離時使用SpringMVC導入Excel表格一樣。Vue前端導入Excel代碼和Vue上傳圖片的代碼沒有區(qū)別,就是將Excel文件傳到后臺,之后就是后臺處理文件的邏輯了,這個就不具體寫了,因為和以前沒區(qū)別。
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Vue進階之CodeMirror的應(yīng)用小結(jié)
CodeMirror支持在線編輯代碼,風格包括js, java, php, c++等等100多種語言,下面這篇文章主要來和大家講講CodeMirror的應(yīng)用,感興趣的可以了解一下2023-06-06vue 修改 data 數(shù)據(jù)問題并實時顯示操作
這篇文章主要介紹了vue 修改 data 數(shù)據(jù)問題并實時顯示操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-09-09VUE中Echarts的resize事件報錯和移除windows的事件問題
這篇文章主要介紹了VUE中Echarts的resize事件報錯和移除windows的事件問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-07-07