簡體   English   中英

Excel中丟失的漢字

[英]Chinese Characters Lost in Excel

我包含以下功能,以獲取包含數據的表格並將其導出到各種互聯網來源的Excel工作表中。 它適用於英文字符,但是當表中包含中文字母時,excel文檔將顯示隨機字符,而不顯示中文。 這與excel V.我的頁面中的編碼有關嗎? 我怎樣才能解決這個問題?

function exportToExcel(table, name)
{
    var uri = 'data:application/vnd.ms-excel;base64,';//application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
    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><!--[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>{table}</table></body></html>';

    if(!table.nodeType)
        table = document.getElementById(table);

    var ctx = {worksheet: name || 'Worksheet', table: table.innerHTML};
    uri += toBase64(format(template, ctx));

    //window.location.href = uri;

    var dlLink = document.createElement('a');
    if (typeof dlLink.download === 'string') {
        document.body.appendChild(dlLink); // Firefox requires the link to be in the body
        dlLink.download = outputFile;
        dlLink.href = uri;
        dlLink.click();
        document.body.removeChild(link); // remove the link when done
    } else {
        location.replace(uri);
    }
}

function toBase64(data)
{
    if (window.btoa)
        return window.btoa(unescape(encodeURIComponent(data)));
    else // IE
    {
        var strUni = data;
            var strUtf = strUni.replace(/[\u0080-\u07ff]/g,
            function(c) {
                var cc = c.charCodeAt(0);
                return String.fromCharCode(0xc0 | cc >> 6, 0x80 | cc & 0x3f);
            })
            .replace(/[\u0800-\uffff]/g,
            function(c) {
                var cc = c.charCodeAt(0);
                return String.fromCharCode(0xe0 | cc >> 12, 0x80 | cc >> 6 & 0x3F, 0x80 | cc & 0x3f);
            });
            return strUtf;

    }
}

function format(template, ctx)
{
    return template.replace(/{(\w+)}/g, function(m, p) { return ctx[p]; });
}

我在模板字符串中添加了head標簽,這告訴excel以UTF-8格式打開文件。 這保留了excel中的中文字符。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM