vue项目
npm i file-saver 下载file包
自己创建exportFile.js文件
/*
* @Author: your name
* @Date: 2021-03-22 17:36:04
* @LastEditTime: 2021-03-23 09:33:44
* @LastEditors: Please set LastEditors
* @Description: In User Settings Edit
* @FilePath: \XKZCproject\src\app\exportFile.js
*/
import FileSaver from "file-saver";
export default class fileSave {
/**
* 导出Excel文件
* @param {*} res 文件流
* @param {*} name 文件名
*/
static getExcel(res, name) {
console.log(res, name);
let blob = new Blob([res], {
type: "application/vnd.ms-excel"
});
console.log(blob);
FileSaver.saveAs(blob, name);
}
/**
* 导出CSV文件
* @param {*} res 文件流
* @param {*} name 文件名
*/
static getCsv(res, name) {
let blob = new Blob([res], {
type: "application/vnd.ms-excel"
});
FileSaver.saveAs(blob, name + ".csv");
}
/**
* 导出图片1
* @param {*} url 图片地址
* @param {*} name 文件名
*/
static getImgURLs(url, name) {
let last = url.substring(url.lastIndexOf("."), url.length);
FileSaver.saveAs(url, `${name}${last}`);
}
/**
* 导出图片2
* @param {*} res 文件流
* @param {*} name 文件名
*/
static downLoadImg(res, filename) {
let blob = new Blob([res], {
type: "image/jpeg"
});
FileSaver.saveAs(blob, `${filename}.jpg`);
}
}
vue项目页面中
在这里插 // 导出excel
// 我这里使用的是 async await 结合 Promise 使用axios请求后面我会附代码
// async downexcel() {
// // res 是 请求响应的 excel 的二进制数据流
// const res = await ChangefeeExcel(
// {
// affectTime: 0, // 请求接口传参
// // 请求接口传参
// },
// {
// responseType: 'arraybuffer', // 响应类型
// }
// );
// let filename = 'excel表格.xls';
// this.fileDownload(res.data, filename); // 调用下面fileDownload方法
// console.log(res.data, 23123);
// },入代码片
#############
二 另一种方法
** async downexcel() {
if (this.dwdata == '') {
this.$message({
showClose: true,
message: '没有可导出的数据!',
type: 'error',
});
return false;
}
if (this.monthtime) {
this.systemDate = this.monthtime;
}
// this.axios({
// method: 'post',
// url: baseURL.url + '/organ/simpleWrite?rang=' + this.$store.state.rang + '&oid=' + this.$store.state.oid + '&creattime=' + this.systemDate,
// responseType: 'blob',
// })
const res= await ChangefeeExcel({
affectTime: 0,
})
let blob = new Blob([res.data], {
type:
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8',
});
let downloadElement = document.createElement('a');
let href = window.URL.createObjectURL(blob);
downloadElement.href = href;
downloadElement.download = '附录三、《费用一览表》.xls'; // xxx.xls/xxx.xlsx
document.body.appendChild(downloadElement);
downloadElement.click();
document.body.removeChild(downloadElement);
window.URL.revokeObjectURL(href);
},**