如何使用JQuery或Javascript导出到CSV数据

Pra*_*een 8 javascript asp.net jquery export-to-csv

我需要的是: 我们在response.d中具有逗号分隔值的价值.现在我想将response.d的数据导出到.csv文件.

我写了这个函数来执行此操作.我已收到response.d中的数据但未导出到.csv文件,因此请为此问题提供解决方案以导出.csv文件中的数据.

function BindSubDivCSV(){ 
  $.ajax({
      type: "POST", 
      url: "../../WebCodeService.asmx / ShowTrackSectorDepartureList", 
      data: "{}", 
      contentType: "application/json; charset=utf-8", 
      dataType: "json",
      success: function (response) {  
        alert(response.d);//export to csv function needed here
      },
      error: function (data) {}
  });
  return false;
}
Run Code Online (Sandbox Code Playgroud)

Ter*_*ung 6

如果您无法控制服务器端的工作方式,这里是我在另一个SO问题中提供的客户端解决方案,等待该OP的接受:使用jQuery和html导出到CSV

您必须考虑某些限制或限制,正如我在那里的回答中提到的那样,其中有更多细节.


这是我提供的相同演示:http: //jsfiddle.net/terryyounghk/KPEGU/

并且让您大致了解脚本的外观.

您需要更改的是如何迭代数据(在另一个问题的情况下是表格单元格)以构建有效的CSV字符串.这应该是微不足道的.

$(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
    });
});
Run Code Online (Sandbox Code Playgroud)


小智 5

使用上面的代码(来自Terry Young),我发现在Opera中它会拒绝给文件起一个名字(简单地称它为“下载”)并且不能始终可靠地工作。

为了使其正常工作,我必须创建一个二进制blob:

    var filename = 'file.csv';
    var outputCSV = 'entry1,entry2,entry3';
    var blobby = new Blob([outputCSV], {type: 'text/plain'});

    $(exportLink).attr({
                'download' : filename,
                'href': window.URL.createObjectURL(blobby),
                'target': '_blank'
                });

    exportLink.click();
Run Code Online (Sandbox Code Playgroud)

另请注意,动态创建“ exportLink”变量不适用于Firefox,因此我必须在HTML文件中添加此变量:

    <div>
        <a id="exportLink"></a>
    </div>
Run Code Online (Sandbox Code Playgroud)

通过上述操作,我已经使用Windows 7 64位和Opera(v22),Firefox(v29.0.1)和Chrome(v35.0.1916.153 m)成功地对此进行了测试。

为了在Internet Explorer上启用类似的功能(尽管方式不太优雅),我不得不使用Downloadify。