-
Notifications
You must be signed in to change notification settings - Fork 0
/
table2CSV.js
74 lines (68 loc) · 2.28 KB
/
table2CSV.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
jQuery.fn.table2CSV = function(options) {
var options = jQuery.extend({
separator: ',',
header: [],
delivery: 'popup' // popup, value
},
options);
var csvData = [];
var headerArr = [];
var el = this;
//header
var numCols = options.header.length;
var tmpRow = []; // construct header avalible array
if (numCols > 0) {
for (var i = 0; i < numCols; i++) {
tmpRow[tmpRow.length] = formatData(options.header[i]);
}
} else {
$(el).filter(':visible').find('th').each(function() {
if ($(this).css('display') != 'none') tmpRow[tmpRow.length] = formatData($(this).html());
});
}
row2CSV(tmpRow);
// actual data
$(el).find('tr').each(function() {
var tmpRow = [];
$(this).filter(':visible').find('td').each(function() {
if ($(this).css('display') != 'none') tmpRow[tmpRow.length] = formatData($(this).html());
});
row2CSV(tmpRow);
});
if (options.delivery == 'popup') {
var mydata = csvData.join('\n');
return popup(mydata);
} else {
var mydata = csvData.join('\n');
return mydata;
}
function row2CSV(tmpRow) {
var tmp = tmpRow.join('') // to remove any blank rows
// alert(tmp);
if (tmpRow.length > 0 && tmp != '') {
var mystr = tmpRow.join(options.separator);
csvData[csvData.length] = mystr;
}
}
function formatData(input) {
// replace " with “
var regexp = new RegExp(/["]/g);
var output = input.replace(regexp, "“");
//HTML
var regexp = new RegExp(/\<[^\<]+\>/g);
var output = output.replace(regexp, "");
if (output == "") return '';
return '"' + output + '"';
}
function popup(data) {
var generator = window.open('', 'csv', 'height=400,width=600');
generator.document.write('<html><head><title>CSV</title>');
generator.document.write('</head><body >');
generator.document.write('<textArea cols=70 rows=15 wrap="off" >');
generator.document.write(data);
generator.document.write('</textArea>');
generator.document.write('</body></html>');
generator.document.close();
return true;
}
};