This repository has been archived by the owner on Mar 10, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathjquery.tabletocsv.js
83 lines (74 loc) · 2.19 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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
/**
* Takes a HTML table and saves its data as a csv
*
* copyright (c) 2013 Scott-David Jones
*/
(function($){
$.fn.tableToCsv = function( options ){
var t = $(this);
if (! t.is('table')) {
throw "selector element is not a table..";
}
var settings = $.extend({
seperator: ',',
fileName: t.attr('id'),
outputheaders: true,
extension: 'csv'
}, options);
var quote = function(string) {
return '"' + string.trim().replace('"', '""') + '"';
}
var csvData = [];
//get headers
if (settings.outputheaders === true) {
var headers = [];
t.find('thead tr').each(function(index, element){
var row = $(this);
row.find('th').each(function(i,e){
var cell = $(this);
headers.push(quote(cell.text()));
});
});
csvData.push(headers);
}
//get the main body of data
t.find('tbody tr').each(function(i,e){
var rowData = [];
var row = $(this);
row.find('td').each(function(i, e){
var cell = $(this);
var text = cell.text();
//if number add else encapsulate with quotes
if ( !isNaN(parseFloat(text)) && isFinite(text) ) {
rowData.push(text);
}
else {
rowData.push(quote(text));
}
});
csvData.push(rowData);
});
var csvString = '';
for (var c in csvData) {
var current = csvData[c];
csvString += current.join(settings.seperator)+"\r\n";
}
// Ludovic Feltz
// https://stackoverflow.com/questions/3665115/create-a-file-in-memory-for-user-to-download-not-through-server
var save = function(filename, data) {
var blob = new Blob([data], {type: 'text/csv'});
if(window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveBlob(blob, filename);
}
else {
var elem = window.document.createElement('a');
elem.href = window.URL.createObjectURL(blob);
elem.download = filename;
document.body.appendChild(elem);
elem.click();
document.body.removeChild(elem);
}
}
save(settings.fileName + "." + settings.extension, csvString)
}
}(jQuery));