excel.js 1.99 KB
Newer Older
wanli's avatar
wanli committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
// 输出base64编码
const base64 = s => window.btoa(unescape(encodeURIComponent(s)));

function checkNullOrUndefined(value) {
    return (!value && value != 0) || (typeof(value) == "undefined")
}

export function exportJsonToExcel({ header = [], headerLabel = "", headerProp = "", jsonData = [], worksheet = 'Sheet', filename = "table-list" } = {}) {
    // 列标题
    let str = '<tr>';
    for (let i = 0; i < header.length; i++) {
        str += `<td>${header[i][headerLabel]}</td>`
    }
    str += "</tr>"

    // 循环遍历,每行加入tr标签,每个单元格加td标签
    for (let i = 0; i < jsonData.length; i++) {
        str += '<tr>';
        for (const obj of header) {
            // 增加\t为了不让表格显示科学计数法或者其他格式
            str += `<td style="mso-number-format: '\@';">${ checkNullOrUndefined(jsonData[i][obj[headerProp]]) ? "" : jsonData[i][obj[headerProp]] + '\t'}</td>`;
        }
        str += '</tr>';
    }
    // Worksheet名
    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>`;
    // 下载模板
    // window.location.href = uri + base64(template);

    // 通过创建a标签实现
    const body = document.getElementsByTagName("body")[0];
    const link = document.createElement("a");
    body.appendChild(link);
    link.href = uri + base64(template);
    link.download = `${filename}.xls`;
    link.click();
    document.body.removeChild(link);
    // link.parentNode.removeChild(link);
}