jQuery/JavaScript代码如何将表导出为CSV文件而不考虑表's大小.看看@jsfiddle链接

How can jQuery/JavaScript code export table to CSV file regardless of the table's size. look @ jsfiddle link

本文关键字:不考虑 链接 @jsfiddle 看看 大小 文件 CSV 代码 JavaScript jQuery      更新时间:2023-10-15

下面是显示表格和代码的链接

http://jsfiddle.net/KPEGU/485/

它显示了我在将表导出到excel CSV时遇到的代码问题。当我单击导出按钮时,会生成CSV文件,但该文件为空,没有数据。


//jsfiddle 上的JS代码

$(document).ready(function () { 
  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 = '","',
        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/csv;charset=utf-8,' + encodeURIComponent(csv);
    $(this)
        .attr({
        'download': filename,
            'href': csvData,
            'target': '_blank'
    });
  }
  // This must be a hyperlink
  $(".export").on('click', function (event) {
    // CSV
    exportTableToCSV.apply(this, [$('#dvData>table'), 'export.csv']);
    // IF CSV, don't do event.preventDefault() or return false
    // We actually need this to be a typical hyperlink
  });
});

确保在表周围放置一个带有dvData id的div。