在后台管理系统中,存在大量的数据表格,有时需要以任意格式导出,这里封装了一个post与get的导出文档函数!!!
1、GET
/**
* 页面【导出】表格 - 【GET】
* @param name 导出页面的名称
* @param host 导出的地址 `/api/center/data/workerRanking/export?id=${id}`
* @returns {HTMLDivElement}
*/
export const downloadExportGet = (name,host) => {
fetch(host, {
method: 'GET',
headers: {
'Content-Type': 'application/get'
}
})
.then(response => response.blob())
.then(blob => {
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `${name}-数据导出[${dateFormat()}].xlsx`; // 下载的文件名
a.click();
window.URL.revokeObjectURL(url);
});
}
/**
* 打开新页面【GET】
*/
window.open(`/api/center/data/workerRanking/export?id=${id}`)
2、POST
/**
* 页面【导出】表格 - 【POST】
* @param name 导出页面的名称
* @param host 导出的地址 `/api/center/data/workerRanking/export`
* @param data 请求的数据
* @returns {HTMLDivElement}
*/
export const downloadExportPost = (name,host,data) => {
fetch(host, {
method: 'POST',
headers: {
'Content-Type': 'application/json;charset=UTF-8'
},
body: JSON.stringify(data)
})
.then(response => response.blob())
.then(blob => {
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `${name}-数据导出[${dateFormat()}].xlsx`; // 下载的文件名
a.click();
window.URL.revokeObjectURL(url);
});
}
3、兼容POST与GET
/**
* 页面【导出】表格
* @param name 导出页面的名称
* @param host 导出的地址 `/api/center/data/workerRanking/export`
* @param data 请求的数据(仅适用于POST请求)
* @param isGet 是否为GET请求(默认false)
* @returns {Promise<HTMLDivElement>}
*/
export const downloadExport = (name, host, data = null, isGet = false) => {
const headers = {};
if (isGet) {
headers['Content-Type'] = 'application/get';
} else {
headers['Content-Type'] = 'application/json;charset=UTF-8';
}
return fetch(host, {
method: isGet ? 'GET' : 'POST',
headers,
body: data ? JSON.stringify(data) : null,
})
.then(response => response.blob())
.then(blob => {
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `${name}-数据导出[${dateFormat()}].xlsx`; // 下载的文件名
a.click();
window.URL.revokeObjectURL(url);
});
};