在中后台页面的开发中少不了excel表格导出功能,以此做个记录:
1.后端返回下载地址:
直接:window.open("文件地址")
或者:window.location.href = "文件地址"
或者 :<a href="文件地址">导出</a>
2.后端返回列表数据(只能下载返回的数据)
安装依赖:
npm install --save xlsx file-saver npm install -D script-loader 如果使用了ts,安装TypeScript定义: npm install @types/file-saver --save-dev
导出接口引入:
import request from '/@/utils/request' import { AxiosResponse } from 'axios' const api = { upLoadFile: '/xxxxx/upLoadFile' } export interface upLoadFileParam { multipartFile: any, } export function upLoadFile(param: upLoadFileParam):Promise<AxiosResponse<IResponse<string>>> { return request({ url: api.upLoadFile, method: 'post', data: param }) }
导出封装:
// 文件导出 export const ExportFile = (data: any, name: any) => { let fileName = name + formatDate(new Date(),'date') // 导出名字+当前日期 let blob = new Blob([data], { type: "application/vnd.ms-excel" }) // 转成blob格式 let link = document.createElement("a") link.download = fileName link.href = URL.createObjectURL(blob) link.style.display = "none" document.body.appendChild(link) link.click() URL.revokeObjectURL(link.href) document.body.removeChild(link) return }
页面使用:
import { fileExport } from '/@/api/all' import { ExportFile } from '/@/utils/all' const handExport = async() => { const getData:any = await fileExport('/management/user/export', {}) ExportFile(getData,'xx列表') }
3.数据一次性返回以后,前端自行组装格式导出
安装依赖:
npm install xlsx --save
npm install --save xlsx file-saver
页面使用:
import FileSaver from 'file-saver' import XLSX from 'xlsx' const handleExport = async () => { let data = JSON.parse(JSON.stringify(formInline.value)) data.pageSize = '' data.pageNo = '' let getData: any = '' let str: any = '' if (getData.code == 200) { tableDataAll.value = getData.data.list // 一次性取回要导出数据 let xlsxParam = { raw: true } let time = new Date() let year = time.getFullYear() let month = time.getMonth() + 1 let day = time.getDate() let name = 'xxx列表' + year + '' + month + '' + day // 文件名加日期 // .excelTable要导出的是哪一个表格 注意这里的 excelTable 是要导出的表格的类名 let wb = XLSX.utils.table_to_book(document.querySelector('.excelTable'), xlsxParam) let wbout = XLSX.write(wb, { bookType: 'xlsx', bookSST: true, type: 'array' }) try { FileSaver.saveAs( new Blob([wbout], { type: 'application/octet-stream' }), name + '.xlsx' ) } catch (e) { // 错误处理 } return wbout } }
标签:xlsx,excel,导出,link,vue3,let,import,data From: https://www.cnblogs.com/foxing/p/16708661.html