【问题标题】:Javascript export table to excel UTF-8 problemJavascript导出表到excel UTF-8问题
【发布时间】:2018-09-04 13:16:26
【问题描述】:

我的导出到 excel 就像一个魅力,除了没有 UTF-8 字符(例如:ÄÖÜÕ)

我使用的代码:

function fnExcelReport()
{
    var tab_text="<table border='2px'><tr bgcolor='#c1292e'>";

    var textRange; var j=0;
    tab = document.getElementById('user_data'); // id of table

    for(j = 0 ; j < tab.rows.length ; j++) 
    {     
        tab_text=tab_text+tab.rows[j].innerHTML+"</tr>";
        //tab_text=tab_text+"</tr>";
    }

    tab_text=tab_text+"</table>";
    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


    var ua = window.navigator.userAgent;
    var msie = ua.indexOf("MSIE "); 

    if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./))      // If Internet Explorer
    {
        txtArea1.document.open("txt/html","replace");
        txtArea1.document.write(tab_text);
        txtArea1.document.close();
        txtArea1.focus(); 
        sa=txtArea1.document.execCommand("SaveAs",true,"Say Thanks to Sumit.xls");
    }  
    else                 //other browser not tested on IE 11
        sa = window.open('data:application/vnd.ms-excel,' + encodeURIComponent(tab_text));  

    return (sa);
}

我尝试将编码添加到 excel 导出中,但遗憾的是没有成功。

tab_text = tab_text + '<head><meta charset="UTF-8" /><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet>';

我也对标签进行了编码。

有什么建议吗? :)。

【问题讨论】:

  • 既然您要走 HTML 表格路线,您可以尝试生成字符代码 HTML 实体,即&amp;#nnn; 格式?但这并不是您真正生成的 Excel 文件,它只是 Excel 愿意打开的东西。
  • 你说得对,我只是需要一些可以导出我的 html 表的东西。那个做我需要的——也不是为了“大规模使用”,它在后端,可以做我需要的所有魔法:)。

标签: javascript excel export-to-excel


【解决方案1】:

很遗憾,escape is almost deprecated,但这是您更快的解决方案: 替换

   sa = window.open('data:application/vnd.ms-excel,' + encodeURIComponent(tab_text));  

   sa = window.open('data:application/vnd.ms-excel,' + escape(tab_text));  

会成功的。

好像是excel和encodeURIComponent的问题 Does VBA have any built in URL decoding? 。您将在此处找到其他解决方案

【讨论】:

  • Ty,这个替换也解决了我的编码问题:)。
猜你喜欢
  • 2017-07-16
  • 2019-08-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-02
  • 1970-01-01
  • 2015-11-04
相关资源
最近更新 更多