前端实现数据导出成excel
·
前端(react/vue)实现数据导出成excel
1. 下载依赖
npm install js-export-excel -D
2. 新建exportExcel.js
import ExportJsonExcel from 'js-export-excel';
/**
* @Event: 获取导出数据
* @description:
* @param config.tableParams<Object>: 表格接口请求参数
* @param config.listKey<String>: 表格数据key,默认为 'list'
* @param config.reqUrl<String>: 表格接口请求地址
* @param config.fetchInit<Object>: 表格接口请求配置,默认为 {method: 'GET', headers: {'content-type': 'application/json'}}
* @author: mhf
* @time: 2025-04-21 10:47:20
**/
export const fetchData = async (config) => {
const {
tableParams,
listKey = 'list',
reqUrl,
fetchInit = {
method: 'GET',
headers: {
'content-type': 'application/json',
Authorization: localStorage.getItem('token'),
},
}
} = config;
try {
const queryParams = new URLSearchParams(tableParams).toString();
const response = await fetch(`${reqUrl}?${queryParams}`, fetchInit);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const tableRes = await response.json();
return tableRes[listKey] || [];
} catch (error) {
console.error('Fetch data failed:', error);
return [];
}
};
/**
* @Event: 前端文件导出
* @description:
* @param reqConfig<Object>: 请求配置对象
* @param reqConfig.tableParams<Object>: 表格接口请求参数
* @param reqConfig.listKey<String>: 表格数据key,默认为 'list'
* @param reqConfig.reqUrl<String>: 表格接口请求地址
* @param config<Object>: 导出配置对象
* @param config.fileName<String>: 文件名
* @param config.sheetFilter<Array>: 表头标题对应的key
* @param config.sheetHeader<Array>: 表头名称
* @author: mhf
* @time: 2025-04-18 18:03:05
**/
export const exportExcel = async (reqConfig, config) => {
const {
fileName,
sheetFilter = [],
sheetHeader = [],
fn = arr => arr
} = config;
const tableData = await fetchData(reqConfig);
if (tableData && tableData.length > 0) {
const processedData = fn(tableData);
const option = {
fileName,
datas: [{
sheetData: JSON.parse(JSON.stringify(processedData)),
sheetName: fileName,
sheetFilter,
sheetHeader,
columnWidth: new Array(sheetHeader.length).fill(20),
}]
};
const toExcel = new ExportJsonExcel(option);
toExcel.saveExcel();
return processedData; // 返回处理后的数据
} else {
console.warn('No data to export');
return [];
}
};
3. 使用
import { exportExcel } from '/src/utils/exportExcel';
const reqConfig = {
tableParams: {
number4page: 99999,
page: 0
},
reqUrl: '/apis/elevator/page',
}
const config = {
fileName: '电梯监测表',
sheetFilter: ['elevatorname', 'modeType', 'runningStateType', 'alarmtypelabel', 'workTime', 'aaa'],
sheetHeader: ['编号', '运行模式', '运行状态', '报警状态', '运行时长', 'aaa'],
fn: (data) => {
return data.map((item) => {
return {
...item,
runningStateType: item.runningstatetype == 1 ? '运行中' : '停止',
modeType: item.modetype === 1 ? '自动' : '手动',
aaa: item.elevatorname + item.elevatorcode,
}
})
}
}
<div onClick={() => exportExcel(reqConfig, config)}>导出</div>
DAMO开发者矩阵,由阿里巴巴达摩院和中国互联网协会联合发起,致力于探讨最前沿的技术趋势与应用成果,搭建高质量的交流与分享平台,推动技术创新与产业应用链接,围绕“人工智能与新型计算”构建开放共享的开发者生态。
更多推荐



所有评论(0)