简体   繁体   English

使用 Javascript 下载 xlsx 格式的 Excel 文件(将 html 表格导出到 Excel)

[英]Download Excel file in xlsx format using Javascript (exporting html tables into Excel)

I am using JS, HTML and CSS to build my application and host it on a server.我正在使用 JS、HTML 和 CSS 来构建我的应用程序并将其托管在服务器上。 I am using the following code to import all the html tables to an excel file in xls format.我正在使用以下代码将所有 html 表导入到 xls 格式的 excel 文件中。

function fnExcelReport(tableNames) {
    var tab_text = "";
    var arrTableNames = tableNames.split("|");
    if (arrTableNames.length > 0) {
        for (var i = 0; i < arrTableNames.length; i++) {

                tab_text = tab_text + "<table border='1px'>";

            tab = document.getElementById(arrTableNames[i]); 


            for (j = 0; j < tab.children.length; j++) {
                tab_text = tab_text + tab.children[j].innerHTML;
            }
            tab_text = tab_text + "</table><br/><br/>";
            tab_text = tab_text.replace(/<A[^>]*>|<\/A>/g, ""); //remove if u want links in your table
            tab_text = tab_text.replace(/<img[^>]*>/gi, ""); // remove if u want images in your table
            tab_text = tab_text.replace(/<input[^>]*>|<\/input>/gi, ""); // reomves input params
        }
    }
    var ua = window.navigator.userAgent;
    var msie = ua.indexOf("MSIE ");

    if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./)) // If Internet Explorer
    {
        if (window.navigator.msSaveBlob) {
            var blob = new Blob([tab_text], {
                type: "data:application/vnd.ms-excel;"
            });
            sa = navigator.msSaveBlob(blob, "report.xls");
        }
    } else //other browser not tested on IE 11
        sa = window.open('data:application/vnd.ms-excel,' + encodeURIComponent(tab_text));

    return (sa);
}

I am able to download the file and open it, but I get the following warning message when I open it:我可以下载该文件并打开它,但在打开它时收到以下警告消息:

Excel 图像上的警告消息

When I click yes, all my data is displayed correctly on the Excel file.当我单击是时,我的所有数据都正确显示在 Excel 文件中。 I don't want to see that warning message.我不想看到那个警告信息。 How do I change my code such that it opens with an xlsx format and removes the warning message?如何更改我的代码,使其以 xlsx 格式打开并删除警告消息?

This is because content is not of type "xls".这是因为内容不是“xls”类型。 ie if excel is of type "xlsx" you will get this error.即如果 excel 是“xlsx”类型,您将收到此错误。 Try with other excel extensions with file name.尝试使用其他带有文件名的 excel 扩展名。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM