【问题标题】:Export table to CSV - string formatting issue into separate cells将表格导出为 CSV - 将字符串格式化问题放入单独的单元格
【发布时间】:2014-10-30 12:57:55
【问题描述】:

我有几个 HTML 表格,我希望允许用户将其内容导出到 csv。

我目前已经实施了这个解决方案,它几乎可以完美运行:

function exportTableToCsv($table, filename) {

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

        tmpColDelim = String.fromCharCode(11),
        tmpRowDelim = String.fromCharCode(0),

        colDelim = ' ',
        rowDelim = '"\r\n"',

        csv = '"' + $rows.map(function (i, row) {
            var $row = $(row),
                $cols = $row.find('td,th');

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

                return text.replace('"', '""');

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

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

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

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

我这样称呼:

$(".ExportSummary").on('click', function () {
    exportTableToCsv.apply(this, [$('#SummaryTable'), 'ExportSummary.csv']);
});

Fiddle Example


现在,我的问题是,我无法通过将 <td> 放在 Excel 中的单独单元格中来使字符串格式正常工作。我只是不知道如何将文本放置在单独的单元格中,因为它被一起映射到整个字符串内容中。

我想要此 JsFiddle 提供的所需输出 - 但此解决方案不提供选择文件名和设置浏览器识别的适当内容类型 (application/csv) 的能力。

感谢任何帮助。提前致谢!

【问题讨论】:

    标签: javascript jquery excel csv


    【解决方案1】:

    http://en.wikipedia.org/wiki/Comma-separated_values#Example

    美国/英国 CSV 文件的小数分隔符是句点/句号,值分隔符是逗号。 欧洲 CSV/DSV 文件小数分隔符是逗号,值分隔符是分号

    我稍微修改了你的脚本:

    function exportTableToCsv($table, filename) {
    ...
            // actual delimiter characters for CSV format
            colDelim = ';',
            rowDelim = '\r\n',
    
            // Grab text from table into CSV formatted string
            csv = $rows.map(function (i, row) {
                var $row = $(row),
                    $cols = $row.find('td,th');
    
                return $cols.map(function (j, col) {
                    var $col = $(col),
                        text = $col.text();
                 ...
    

    http://jsfiddle.net/mu5g1a7x/2/

    如果我理解正确,请告诉我。

    【讨论】:

      猜你喜欢
      • 2019-06-03
      • 2016-03-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-23
      • 1970-01-01
      • 2019-07-11
      • 1970-01-01
      相关资源
      最近更新 更多