vue3+TypeScript实现导出Excel功能
生活随笔
收集整理的這篇文章主要介紹了
vue3+TypeScript实现导出Excel功能
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
上一篇博客👉鏈接在這,我們使用vue3+ts實現了導入的功能,接下來,還是使用同一個組件(element-plus上傳組件)來實現導出,在上篇博客中,我們在使用這個組件的同時寫了一個下載模板的功能,接下來,這篇博客,我們就幫助大家完善下載模板的功能以及實現導出的功能。??????
一、效果展示
我們通過兩個按鈕來實現導入導出功能、具體模板的樣式如下
具體樣式,請參考上篇博客
二、模板下載
<el-buttonclass="excel-btn"size="small"type="primary"icon="download"@click="downloadTemplate('導入用戶模板文件.xlsx')">點擊下載</el-button> //接口文件 export const downloadTemplate = fileName =>{return service({url: 'XXXX',method: 'post',params: {fileName: fileName,},responseType: 'blob',}).then(res => {handleFileError(res, fileName);}); }const handleFileError = (res, fileName) => {if (typeof res.data !== 'undefined') {if (res.data.type === 'application/json') {const reader = new FileReader();reader.onload = function () {const message = JSON.parse(reader.result).msg;ElMessage({showClose: true,message: message,type: 'error',});};reader.readAsText(new Blob([res.data]));}} else {var downloadUrl = window.URL.createObjectURL(new Blob([res]));var a = document.createElement('a');a.style.display = 'none';a.href = downloadUrl;a.download = fileName;var event = new MouseEvent('click');a.dispatchEvent(event);} };以上就是下載模板的功能實現
導出文件
<el-buttonclass="excel-btn"size="small"icon="download"@click="handleExcelExport('用戶列表.xlsx')">導出</el-button> const tableData = ref([]); const handleExcelExport = fileName => {if (!fileName || typeof fileName !== 'string') {fileName = 'ExcelExport.xlsx';}exportExcel(tableData.value, fileName); };//接口export const exportExcel = (tableData, fileName) => {return service({url: 'XXX',method: 'post',data: {fileName: fileName,infoList: tableData,},responseType: 'blob',}).then(res => {handleFileError(res, fileName);}); }; const handleFileError = (res, fileName) => {if (typeof res.data !== 'undefined') {if (res.data.type === 'application/json') {const reader = new FileReader();reader.onload = function () {const message = JSON.parse(reader.result).msg;ElMessage({showClose: true,message: message,type: 'error',});};reader.readAsText(new Blob([res.data]));}} else {var downloadUrl = window.URL.createObjectURL(new Blob([res]));var a = document.createElement('a');a.style.display = 'none';a.href = downloadUrl;a.download = fileName;var event = new MouseEvent('click');a.dispatchEvent(event);} };這樣我們就實現了導出功能,同時很多時候我們可能會遇到按需導出的需求,這是,我們只需要在接口中傳遞相應的參數即可。
總結
以上是生活随笔為你收集整理的vue3+TypeScript实现导出Excel功能的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【基础练习】codevs1506 传话题
- 下一篇: SpringBoot后端+Vue之Ant