如何使用JQuery或Javascript导出到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; } 

如果你无法控制服务器端如何工作,这里是我在另一个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 }); }); 

使用上面的代码(来自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(); 

另请注意,动态创建“exportLink”变量不适用于Firefox,所以我必须在我的HTML文件中使用它:

  

使用上面的内容,我已经使用Windows 7 64bit和Opera(v22),Firefox(v29.0.1)和Chrome(v35.0.1916.153 m)成功测试了这一点。

为了在Internet Explorer上启用类似的function(尽管效果不那么优雅),我不得不使用Downloadify。