首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用JQuery或Javascript将数据导出到CSV

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

Stack Overflow用户
提问于 2013-04-18 11:54:04
回答 1查看 22.6K关注 0票数 8

我需要的东西:我们在response.d中有值,即逗号分隔的值。现在,我想将response.d的数据导出到.csv文件。

我编写了这个函数来执行这个任务。我已经收到了response.d中的数据,但没有导出到.csv文件中,因此给出了解决此问题的解决方案,以导出.csv文件中的数据。

代码语言:javascript
复制
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;
}
EN

回答 1

Stack Overflow用户

发布于 2013-04-26 07:44:10

如果您无法控制服务器端的工作方式,下面是我在另一个这样的问题中提供的客户端解决方案,等待OP的接受:Export to CSV using jQuery and html

有一些限制或限制,您必须考虑,正如我在回答中提到的,这里有更多的细节。

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

让你大致了解一下剧本是什么样子。

需要更改的是如何迭代数据(在另一个问题中是表单元格)来构造有效的CSV字符串。应该是很简单的。

代码语言:javascript
复制
$(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
    });
});
票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/16082231

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档