封装exportExcel文件
- utils/exportExcel.js
import moment from "moment";
import request from "@/utils/request";
import {
Message
} from 'element-ui';
// 优化项 可优化为一个方法
/**
*
* @param {*} url // 请求地址
* @param {*} query // 请求参数
* @param {*} filename // 文件名
* @param {*} method // 请求方式
* @param {*} formatFileName // 是否格式化文件名
* @param {*} fileType // 文件类型
* @returns
*/
export function exportExcel(url, query, filename, method = 'GET', formatFileName = true, fileType = 'xlsx') {
const params = {
headers: {
"Content-Type": "application/json; application/octet-stream"
},
responseType: "blob", // 服务器返回的数据类型
url: url,
method,
}
if (method === 'POST') {
params.data = query;
} else {
params.params = query;
}
console.log(fileType)
return exportFile(params, filename, formatFileName, fileType)
}
function exportFile(params, filename, formatFileName, fileType) {
return request(params)
.then(response => {
if (response.type == "application/json") {
// Message.warning("导出超时");
// 将blob转化成json 格式
const reader = new FileReader()
let parseObj = null
reader.readAsText(response, 'utf-8')
reader.onload = function() {
parseObj = JSON.parse(reader.result)
Message.error(parseObj.msg)
}
return false;
}
const blob = new Blob([response], {
type: "application/excel"
});
let fileName = '';
if (formatFileName) {
fileName = filename + moment(new Date()).format("YYYYMMDDHHmmss") + "." + fileType;
} else {
fileName = filename + "." + fileType;
}
if ("download" in document.createElement("a")) {
const link = document.createElement("a");
link.download = fileName;
link.style.display = "none";
link.href = URL.createObjectURL(blob);
document.body.appendChild(link);
link.click();
URL.revokeObjectURL(link.href);
document.body.removeChild(link);
} else {
// 其他浏览器
navigator.msSaveBlob(blob, fileName);
}
return response;
}).catch(() => {
return 'error';
});
}
- 使用
import { exportExcel } from '@/utils/exportExcel.js';
export default {
data() {
return {
}
},
methods: {
handleExport() {
exportExcel('接口路径', 传递的参数, '文件名');
}
},