js 导出 excel window.location.href 没有生成文件名字的问题

今天生产环境发生了一件奇怪的事情,之前写好的 excel 导出的 js 代码竟然导出的文件没有文件名字,之前都是随机字符串的。

代码

function tableToExcelExp(str, sheetName) {
    var uri = 'data:application/vnd.ms-excel;base64,';
    var 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><meta charset="UTF-8"><!--[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]-->' +
        ' <style type="text/css">' +
        'table td {' +
        'border: 1px solid #000000;' +
        'width: 200px;' +
        'height: 30px;' +
        ' text-align: center;' +
        // 'background-color: #4f891e;' +
        // 'color: #ffffff;' +
        ' }' +
        '</style>' +
        '</head><body ><table class="excelTable">'+str+'</table></body></html>';
    var ctx = {worksheet: sheetName };
    window.location.href = uri + base64(format(template, ctx));
}

被迫修改为

function tableToExcelExp(str, sheetName,fileName) {
    var uri = 'data:application/vnd.ms-excel;base64,';
    var 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><meta charset="UTF-8"><!--[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]-->' +
        ' <style type="text/css">' +
        'table td {' +
        'border: 1px solid #000000;' +
        'width: 200px;' +
        'height: 30px;' +
        ' text-align: center;' +
        // 'background-color: #4f891e;' +
        // 'color: #ffffff;' +
        ' }' +
        '</style>' +
        '</head><body ><table class="excelTable">'+str+'</table></body></html>';
    var ctx = {worksheet: sheetName };
    var alink = $('<a style="display:none"></a>').appendTo('body');
    alink[0].href = uri + base64(format(template, ctx));
    alink[0].download = fileName;
    alink[0].click();
    alink.remove();
}

但是不清楚为什么会这个样子,记录下,有清楚的朋友可以帮忙解答下。

猜你喜欢

转载自blog.csdn.net/qq_26276667/article/details/111473842