前端處理二進制流文件導出為excel表代碼示例
更新時間:2023年08月03日 11:07:09 作者:劉小蟲_
這篇文章主要給大家介紹了關于前端處理二進制流文件導出為excel表的相關資料,后臺管理系統(tǒng),常會出現導出excel表格功能,需要的朋友可以參考下
將后端返回的二進制流文件
導出為excel表用的時候直接調用showConfirm函數即可
最后效果

代碼示例
export function getExport(param) {
get('/api/xdata/v1/basic/auth/excel', { ...param }).then((res) => {
// let name = getFileName(url);
let name = 'export.xlsx';
console.log('res', res);
// let u = window.URL.createObjectURL(new Blob([res]));
const type = 'application/vnd.ms-excel;charset=utf-8'; //excel文件
let u = window.URL.createObjectURL(new Blob([res], { type: type }));
let a = document.createElement('a');
a.download = name;
a.href = u;
console.log(a);
a.style.display = 'none';
document.body.appendChild(a);
a.click();
a.remove();
// setTimeout(myDlWarn, 0);
});
}
export function showConfirm(text, exportParams) {
confirm({
title: `您確認要導出${text}嗎`,
icon: <ExclamationCircleOutlined />,
content: '',
okText: '確認',
okType: 'primary',
cancelText: '取消',
onOk() {
getExport(exportParams);
},
onCancel() {
console.log('Cancel');
},
});
}get接口是自己封裝的,封裝如下
/**
* 從 cookie 中獲取數據
* @param {string} cname cname
*/
export const getCookie = (cname) => {
var name = cname + '=';
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i].trim();
if (c.indexOf(name) === 0) {
return c.substring(name.length, c.length);
}
}
return '';
};
const ajax = (method, url, data, options = {}) => {
const isPost = method === 'post';
const isPut = method === 'put';
const isPatch = method === 'patch';
const isGet = method === 'get';
const sentOptions = {
url,
method,
withCredentials: true, // 允許跨域
credentials: 'include',
headers: {
'X-Request-By': 'ERApplication',
'X-Requested-With': 'XMLHttpRequest',
'X-Region': 'bj',
'X-From': 'web',
},
...options,
};
if (isPost || isPatch) {
sentOptions.headers['Content-Type'] = 'application/x-www-form-urlencoded';
sentOptions.data = JSON.stringify(data);
} else if (isPut) {
sentOptions.data = JSON.stringify(data);
} else if (isGet) {
sentOptions.headers['Content-Type'] = 'utf-8';
sentOptions.params = data;
}
return new Promise((resolve, reject) => {
axios(sentOptions)
.then((response) => {
resolve(response.data);
.catch((error) => {
console.log('catch');
reject(error);
});
});
};
export const get = (url, data = {}) => {
return ajax('get', BASE_URL + url, data, { responseType: 'blob' });
};總結
到此這篇關于前端處理二進制流文件導出為excel表的文章就介紹到這了,更多相關前端二進制流導出excel內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
JavaScript setTimeout()基本用法有哪些
這篇文章主要介紹了JavaScript setTimeout()基本用法有哪些,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2020-11-11

