通过前端将table数据导出为excel表
第一种使用js-export-excel
利用js-export-excel
插件可快速实现
一、首先下载插件
npm install js-export-excel -S
二、配置
const CreateExcel = require("js-export-excel");
const ExportExcel = ( tableData, columns, name) => {
let excelData = [];
let option={}
tableData.forEach((v,k) => {
let o = {};
/*
* 需要将数据处理为键值对形式
* k: 表头
* v: 表头对应数据
*/
columns.forEach(_columns => {
o[_columns.title] = v[_columns.dataIndex] || ''
});
excelData.push(o)
});
// 文件名
option.fileName = name;
const rowHeader = columns.map(_colums => _colums.title)
option.datas = [
{
sheetData: excelData,
sheetName: 'sheet',
// 可用来过滤只需要显示的表头数据
// sheetFilter: [],
// 表头
sheetHeader: rowHeader
}
];
const toExcel = new CreateExcel(option);
toExcel.saveExcel();
}
export default ExportExcel;
tableData格式
columns格式
const columns = [
{
title: t('ID'),
dataIndex: 'id',
key:"id"
},
{
title: t('Provider-API-ID'),
dataIndex: 'provider_API_id',
key: 'provider_API_id',
},
{
title: t('Resouce-Account'),
dataIndex: 'resouce_account',
key: 'resouce_account',
},
{
title: t('DX-ID'),
dataIndex: 'DX_ID',
key: 'DX_ID',
},
{
title: t('DX-Name'),
dataIndex: 'name',
key: 'name',
},
{
title: t('Region'),
dataIndex: 'region',
key: 'region',
},
{
title: t('Location'),
dataIndex: 'location',
key: 'location',
},
{
title: t('BandWidth'),
dataIndex: 'bandwidth_total',
key: 'bandwidth_total',
},
{
title: t('Con-BW-Specification'),
dataIndex: 'con_bw_specification',
key: 'con_bw_specification',
},
];
处理后的excelData格式
sheetHeader表头格式
三、调用
ExportExcel(tableData, columns, 'excel表格');
第二种使用exceljs
import ExcelJS from 'exceljs';
/**
* 导出Excel表格
* @param {Array} tableData 表数据
* @param {Array} columns 表头
* @param {String} name 表名称
* @param {Array} colWidth 列宽
*/
const exportExcel = async ({
tableData = [],
columns = [],
name = "",
colWidth = []
}) => {
const workbook = new ExcelJS.Workbook();
const worksheet = workbook.addWorksheet('Sheet');
// 表头
const headerRow = worksheet.addRow(columns.map(column => column.title));
// 表头样式
headerRow.eachCell(cell => {
// cell.font = { bold: true };
cell.alignment = { horizontal: 'center' };
});
// 数据
tableData.forEach(rowData => {
worksheet.addRow(columns.map(column => rowData[column.dataIndex] || ''));
});
// 列宽
colWidth.forEach((width, index) => {
worksheet.getColumn(index + 1).width = width;
});
// 生成Excel文件
const buffer = await workbook.xlsx.writeBuffer();
saveExcelFile(buffer, name);
};
// 下载Excel文件
const saveExcelFile = (buffer, name) => {
const blob = new Blob([buffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
const url = window.URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', `${name}.xlsx`);
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
window.URL.revokeObjectURL(url);
};
export default exportExcel;