-
Notifications
You must be signed in to change notification settings - Fork 9
/
jquery.tabletoCSV.js
45 lines (40 loc) · 1.17 KB
/
jquery.tabletoCSV.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
jQuery.fn.tableToCSV = function() {
var clean_text = function(text){
text = text.replace(/"/g, '""');
return '"'+text+'"';
};
$(this).each(function(){
var table = $(this);
var caption = $(this).find('caption').text();
var title = [];
var rows = [];
$(this).find('tr').each(function(){
var data = [];
$(this).find('th').each(function(){
var text = clean_text($(this).text());
title.push(text);
});
$(this).find('td').each(function(){
var text = clean_text($(this).text());
data.push(text);
});
data = data.join(",");
rows.push(data);
});
title = title.join(",");
rows = rows.join("\n");
var csv = title + rows;
var uri = 'data:text/csv;charset=utf-8,' + encodeURIComponent(csv);
var download_link = document.createElement('a');
download_link.href = uri;
var ts = new Date().getTime();
if(caption==""){
download_link.download = ts+".csv";
} else {
download_link.download = caption+"-"+ts+".csv";
}
document.body.appendChild(download_link);
download_link.click();
document.body.removeChild(download_link);
});
};