下載文件我們常用的方式有之間跳轉頁面下載,二進制文件流下載,今天總結一下使用“xlsx”插件下載(快捷方便,操作簡單,不需要請求後臺)
- 安裝相關依賴
npm install --save xlsx file-saver
- 組件裏頭引入
import FileSaver from 'file-saver'
import XLSX from 'xlsx'
- 組件methods裏寫一個方法
exportExcel () {
var wb = XLSX.utils.table_to_book(document.querySelector('#out-table')) // 這個id是表格的id
var wbout = XLSX.write(wb, { bookType: 'xlsx', bookSST: true, type: 'array' })
try {
FileSaver.saveAs(new Blob([wbout], { type: 'application/octet-stream' }), '表格名稱.xlsx')
} catch (e) { if (typeof console !== 'undefined') console.log(e, wbout) }
return wbout
},
- 直接調用這個方法就開始下載了