导出的XLS文件打开时编码错误,或者所有数据都在一列中打开

时间:2017-11-15 14:03:50

标签: javascript html excel csv

我有一个用JS编写的函数,它生成一个XLS文件,可以从HTML表中下载。一切正常,但如果直接打开XLS文件,则一行中的所有值都显示在一列中。但是,如果我在charset声明中遗漏了BOM,那么这些值会出现在单独的列中,但它会使用特殊字符混乱编码。

以下是我使用的代码:

function exportTableToCSV($table, filename) {

    var $rows = $table.find('tr:has(td)'),

        // Temporary delimiter characters unlikely to be typed by keyboard
        // This is to avoid accidentally splitting the actual contents
        tmpColDelim = String.fromCharCode(11), // vertical tab character
        tmpRowDelim = String.fromCharCode(0), // null character

        // actual delimiter characters for CSV format
        colDelim = '"\t"',
        rowDelim = '"\r\n"',

        // Grab text from table into CSV formatted string
        csv = '"' + $rows.map(function (i, row) {
            var $row = $(row),
                $cols = $row.find('td');

            return $cols.map(function (j, col) {
                var $col = $(col),
                    text = $col.text();

                return text.replace('"', '""'); // escape double quotes

            }).get().join(tmpColDelim);

        }).get().join(tmpRowDelim)
            .split(tmpRowDelim).join(rowDelim)
            .split(tmpColDelim).join(colDelim) + '"',

        // Data URI
        csvData = 'data:application/ms-excel;charset=utf-8,\ufeff' + encodeURIComponent(csv);

    $(this)
        .attr({
        'download': filename,
            'href': csvData,
            'target': '_blank'
    });
}

// This must be a hyperlink
$(".excelExport").on('click', function (event) {
    // CSV
    $(".timeStampUt").show();
    exportTableToCSV.apply(this, [$('#xlsData'), 'oszido-<?php echo $now_date1; ?>-<?php echo $now_time1; ?>.xls']);  //Change name of excel as per your need
    $(".timeStampUt").hide();

    if($(this).hasClass("utExcelExport")) {
        changeValue('ClosureOfAid', 'no', 'utExcelExport-retired-isNotNull');
    }
    // IF CSV, don't do event.preventDefault() or return false
    // We actually need this to be a typical hyperlink
});

如果我尝试从Data&gt;从Text打开它并从那里打开XLS,一切正常。这对我来说很好,但是我的客户希望通过打开文件直接工作。我怎么处理这个?

0 个答案:

没有答案