如何使用 JQuery 或 Javascript 将数据导出到 CSV
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16082231/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to data Export to CSV using JQuery or Javascript
提问by Praveen
What I needed:We have value in the response.d that is comma deliminated value. Now I want to export the data of response.d to .csv file.
我需要的是:我们在 response.d 中有值,即逗号分隔值。现在我想将 response.d 的数据导出到 .csv 文件。
I have written this function to perform this. I have received the data in response.d but not exporting to the .csv file, so give the solution for this problem to export data in .csv file.
我已经编写了这个函数来执行这个。我在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;
}
回答by Terry Young
In case you have no control over how the server-side works, here is a client-side solution that I have offered in another SO question, pending for that OP's acceptance: Export to CSV using jQuery and html
如果您无法控制服务器端的工作方式,这里是我在另一个 SO 问题中提供的客户端解决方案,等待该 OP 的接受:使用 jQuery 和 html 导出到 CSV
There are certain restrictions or limitations you will have to consider, as I have mentioned in my answer over there, which has more details.
您必须考虑某些限制或限制,正如我在那边的回答中提到的,其中有更多详细信息。
This is the same demoI have offered: http://jsfiddle.net/terryyounghk/KPEGU/
这与我提供的演示相同:http: //jsfiddle.net/terryyounghk/KPEGU/
And to give you a rough idea of what the script looks like.
并让您大致了解脚本的外观。
What you need to change is how you iterate your data (in the other question's case it was table cells) to construct a valid CSV string.This should be trivial.
您需要更改的是如何迭代数据(在另一个问题的情况下是表格单元格)以构建有效的 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
});
});
回答by Glen Walker
Using the code above (from Terry Young) I found that in Opera it would refuse to give the file a name (simply calling it "download") and would not always work reliably.
使用上面的代码(来自 Terry Young)我发现在 Opera 中它会拒绝给文件一个名字(简单地称它为“下载”)并且不能总是可靠地工作。
To get it to work I had to create a binary blob:
为了让它工作,我必须创建一个二进制 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();
Also note that creating the "exportLink" variable on the fly would not work with Firefox so I had to have this in my HTML file:
另请注意,即时创建“exportLink”变量不适用于 Firefox,因此我必须在我的 HTML 文件中包含它:
<div>
<a id="exportLink"></a>
</div>
Using the above I have successfully tested this using Windows 7 64bit and Opera (v22), Firefox (v29.0.1), and Chrome (v35.0.1916.153 m).
使用上述内容,我已成功地使用 Windows 7 64 位和 Opera (v22)、Firefox (v29.0.1) 和 Chrome (v35.0.1916.153 m) 对此进行了测试。
To enable similar functionality (albeit in a far less elegant manner) on Internet Explorer I had to use Downloadify.
为了在 Internet Explorer 上启用类似的功能(虽然方式不太优雅),我不得不使用 Downloadify。