js實現表格數據導出到excel文件

如下代碼是工具類文件exportToExcel.js 內容,實現場景是將antd的table數據導出成excel文件(其餘UI框架的table也一樣適用,只需傳入合適的數據)。
exportToExcel() 方法接受  表格列數據、 表格數據 和 導出文件名 3個參數, 表格列數據和表格數據都直接使用 Table 組件中的columns和dataSource的數據,無需更改。文件名默認後綴爲.xls。 如有須要轉義的數據, 自行拓展。。
這裏用到了一個隱藏的 <a id="exportToExcel" style="visibility:hidden"></a>  標籤, 能夠定義在index.html或者本身喜歡的地方
 
import moment from 'moment';

 

function base64(s) {
return window.btoa(unescape(encodeURIComponent(s)));
}

 

function exportToExcel(columns, data, fileName) {
let str = '<tr><td>';
columns.forEach((item, index) => {
if (index === columns.length - 1) {
str += `${item.title}</td></tr>`;
} else {
str += `${item.title}</td><td>`;
}
});
data.forEach((item) => {
str += '<tr>';
columns.forEach((column) => {
// 處理時間戳格式數據
const value = (/[d|D]ate|[t|T]ime/.test(column.dataIndex) && typeof item[column.dataIndex] === 'number') ?
moment(item[column.dataIndex]).format('YYYY-MM-DD hh:mm:ss') : item[column.dataIndex];
str += `<td>${`${value || ''}\t`}</td>`;
});
str += '</tr>';
});
// Worksheet名字
const worksheet = 'Sheet1';
const uri = 'data:application/vnd.ms-excel;base64,';
// 表格模板數據
const template = `<html xmlns:o="urn:schemas-microsoft-com:office:office"
xmlns:x="urn:schemas-microsoft-com:office:excel"
xmlns="http://www.w3.org/TR/REC-html40">
<head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet>
<x:Name>${worksheet}</x:Name>
<x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet>
</x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]-->
</head><body><table>${str}</table></body></html>`;

 

document.getElementById('exportToExcel').href = uri + base64(template);
// 補後綴
const name = fileName.split('.')[1] ? fileName : `${fileName}.xls`;
document.getElementById('exportToExcel').download = name;
document.getElementById('exportToExcel').click();
}

 

export default exportToExcel;
相關文章
相關標籤/搜索