forked from angular-ui/ui-grid
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathng-grid-csv-export.js
80 lines (79 loc) · 3.31 KB
/
ng-grid-csv-export.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
// Todo:
// 1) Make the button prettier
// 2) add a config option for IE users which takes a URL. That URL should accept a POST request with a
// JSON encoded object in the payload and return a CSV. This is necessary because IE doesn't let you
// download from a data-uri link
//
// Notes: This has not been adequately tested and is very much a proof of concept at this point
function ngGridCsvExportPlugin (opts) {
var self = this;
self.grid = null;
self.scope = null;
self.init = function(scope, grid, services) {
self.grid = grid;
self.scope = scope;
function showDs() {
var keys = [];
for (var f in grid.config.columnDefs) { keys.push(grid.config.columnDefs[f].field);}
var csvData = '';
function csvStringify(str) {
if (str == null) { // we want to catch anything null-ish, hence just == not ===
return '';
}
if (typeof(str) === 'number') {
return '' + str;
}
if (typeof(str) === 'boolean') {
return (str ? 'TRUE' : 'FALSE') ;
}
if (typeof(str) === 'string') {
return str.replace(/"/g,'""');
}
return JSON.stringify(str).replace(/"/g,'""');
}
function swapLastCommaForNewline(str) {
var newStr = str.substr(0,str.length - 1);
return newStr + "\n";
}
for (var k in keys) {
csvData += '"' + csvStringify(keys[k]) + '",';
}
csvData = swapLastCommaForNewline(csvData);
var gridData = grid.data;
for (var gridRow in gridData) {
for ( k in keys) {
var curCellRaw;
if (opts != null && opts.columnOverrides != null && opts.columnOverrides[keys[k]] != null) {
curCellRaw = opts.columnOverrides[keys[k]](gridData[gridRow][keys[k]]);
}
else {
curCellRaw = gridData[gridRow][keys[k]];
}
csvData += '"' + csvStringify(curCellRaw) + '",';
}
csvData = swapLastCommaForNewline(csvData);
}
var fp = grid.$root.find(".ngFooterPanel");
var csvDataLinkPrevious = grid.$root.find('.ngFooterPanel .csv-data-link-span');
if (csvDataLinkPrevious != null) {csvDataLinkPrevious.remove() ; }
var csvDataLinkHtml = "<span class=\"csv-data-link-span\">";
csvDataLinkHtml += "<br><a href=\"data:text/csv;charset=UTF-8,";
csvDataLinkHtml += encodeURIComponent(csvData);
csvDataLinkHtml += "\" download=\"Export.csv\">CSV Export</a></br></span>" ;
fp.append(csvDataLinkHtml);
}
setTimeout(showDs, 0);
scope.catHashKeys = function() {
var hash = '';
for (var idx in scope.renderedRows) {
hash += scope.renderedRows[idx].$$hashKey;
}
return hash;
};
if (opts.customDataWatcher) {
scope.$watch(opts.customDataWatcher, showDs);
} else {
scope.$watch(scope.catHashKeys, showDs);
}
};
}