-
Notifications
You must be signed in to change notification settings - Fork 65
Expand file tree
/
Copy pathexport2CSV.html
More file actions
309 lines (250 loc) · 8.8 KB
/
export2CSV.html
File metadata and controls
309 lines (250 loc) · 8.8 KB
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
<!DOCTYPE html>
<!--
Copyright 2020 SAS Institute Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript" src="../util/messagingUtil.js"></script>
<script type="text/javascript" src="../util/contentUtil.js"></script>
<style>
html {
overflow: hidden;
}
html,
body,
div {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
}
div {
position: relative;
}
.gen_btn {
padding: 8px;
background-color: #0378cd;
color: white;
font-family: arial;
font-size: 13px;
border: 0px;
border-radius: 4px;
}
.gen_btn:hover {
background-color: #0494fb;
cursor: pointer;
}
</style>
<script type="text/javascript">
"use strict";
var _resultData = null;
var _resultName = null;
var _selections = null;
var _data = null;
// This is used to take advantage of Google's NumberFormat function
google.charts.load('current', { 'packages': ['corechart'] });
va.messagingUtil.setOnDataReceivedCallback(onDataReceived);
// Retrieve data and store message received from VA
function onDataReceived(resultData) {
_data = null;
_resultData = resultData;
_resultName = resultData.resultName;
if (!_resultData.data.length) {
va.messagingUtil.postInstructionalMessage(
_resultName,
"Optional VA parameters:\n" +
"(1) _downloaded_file_name (no extension, default: DownloadedFromVA)\n" +
"(2) _show_column_labels (YES/NO, default: YES)\n" +
"(3) _transpose_data (YES/NO, default: NO)"
);
return;
}
}
function treatMissingValues(data, columns) {
for (var c = 0; c < columns.length; c++) {
var colInfo = columns[c];
if (colInfo.type == "string") {
for (var r = 0; r < data.length; r++) {
if (data[r][c] == "(missing)") data[r][c] = "";
}
}
}
}
// Returns JSON:
// [{<col0-label>:<col0-row0>, ..., <colC-label>:<colC-row0>}, ..., {<col0-label>:<col0-rowR>, ..., <colC-label>:<colC-rowR>}]
function createFormattedJSON(data, columns) {
var dataArray = [];
for (var r = 0; r < data.length; r++) {
dataArray.push({});
for (var c = 0; c < data[r].length; c++) {
var formatter = getNumberFormatter(columns[c]);
dataArray[r][columns[c].label] = (formatter ? formatter.formatValue(data[r][c]) : data[r][c]);
}
}
return dataArray;
}
function getNumberFormatter(colInfo) {
var formatter = null;
if (colInfo.format) {
if (colInfo.format.name == "DOLLAR") {
formatter = new google.visualization.NumberFormat({
prefix: '$',
fractionDigits: colInfo.format.precision
});
}
else if (colInfo.format.name == "COMMA") {
formatter = new google.visualization.NumberFormat({
fractionDigits: colInfo.format.precision
});
}
else if (colInfo.format.name == "F") {
formatter = new google.visualization.NumberFormat({
groupingSymbol: '',
fractionDigits: colInfo.format.precision
});
}
else if (colInfo.format.name == "PERCENT") {
var pattern = '#,###';
if (colInfo.format.precision > 0) {
pattern += ".";
for (var j = 0; j < colInfo.format.precision; j++)
pattern += "#";
}
pattern += "%";
formatter = new google.visualization.NumberFormat({
pattern: pattern
});
}
}
return formatter;
}
// Code below based on: http://jsfiddle.net/hybrid13i/JXrwM/
function JSONToCSV(JSONData, ShowHeader, Transpose) {
// If JSONData is not an object then JSON.parse will parse the JSON string in an Object
var arrData = typeof JSONData != 'object' ? JSON.parse(JSONData) : JSONData;
var CSV = '';
if (Transpose) {
// [{<col0-label>:<col0-row0>, ..., <colC-label>:<colC-row0>}, ..., {<col0-label>:<col0-rowR>, ..., <colC-label>:<colC-rowR>}]
// 1st loop is to extract each column
for (var c = 0; c < Object.keys(arrData[0]).length; c++) {
var row = "";
var colName = Object.keys(arrData[0])[c];
if (ShowHeader) {
row += '"' + colName + '",';
}
// 2nd loop will extract each row value and convert it to comma-seprated strings
for (var r = 0; r < arrData.length; r++) {
row += '"' + arrData[r][colName] + '",';
}
// remove the extra comma at the end
row = row.slice(0, - 1);
// add a line break after each row
CSV += row + '\r\n';
}
}
else {
// This condition will generate the Label/Header
if (ShowHeader) {
var row = "";
// This loop will extract the column labels (keys) from 1st object of the array
for (var key in arrData[0]) {
//Now convert each value to string and comma-seprated
row += '"' + key + '",';
}
// remove the extra comma at the end
row = row.slice(0, -1);
// append Label row with line break
CSV += row + '\r\n';
}
// 1st loop is to extract each row
for (var i = 0; i < arrData.length; i++) {
var row = "";
// 2nd loop will extract each column value and convert to comma-seprated strings
for (var key in arrData[i]) {
row += '"' + arrData[i][key] + '",';
}
// remove the extra comma at the end
row = row.slice(0, - 1);
// add a line break after each row
CSV += row + '\r\n';
}
}
return CSV;
}
function DownloadCSV(CSV, FileName) {
// Set Report title in first row or line
// Generate a file name
var fileName = "MyReport";
if (FileName != "") {
// This will remove the blank-spaces from the title and replace it with an underscore
fileName = FileName.replace(/ /g, "_");
}
// Initialize file format you want csv or xls
var uri = 'data:text/csv;charset=utf-8,' + escape(CSV);
//var uri = 'data:application/octet-stream,' + escape(CSV); // arbitrary binary data
// Now the little tricky part.
// you can use either>> window.open(uri);
// but this will not work in some browsers
// or you will not get the correct file extension
//this trick will generate a temp/hidden <a /> tag and programmatically click on the link
var link = document.createElement("a");
link.href = uri;
//set the visibility hidden so it will not affect on your web-layout
link.style = "visibility:hidden";
link.download = fileName + ".csv";
//this was not necessary before, but for some reason download does not work without it now
var txt = document.createTextNode("Download");
link.appendChild(txt);
//this part will append the anchor tag and remove it after automatic click
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
function download() {
_selections = va.contentUtil.initializeSelections(_resultData); // needed to remove eventual brush columns
// Process result data: leave data in the right format for downloading
treatMissingValues(_resultData.data, _resultData.columns);
// Two options: transposed or not - this could be a parameter to the DDC
// Uncomment the desired option
//
// Transposed option:
// data = createTransposedFormattedJSON(_resultData.data, _resultData.columns);
// console.log("formatted and transposed:", data);
//
// Not transposed option (default tabular view):
var data = createFormattedJSON(_resultData.data, _resultData.columns);
console.log("formatted (not transposed):", data);
if (!data.length)
return;
var vaParameters = va.contentUtil.getVAParameters(_resultData);
var fileName = vaParameters._downloaded_file_name;
var showHeader = vaParameters._show_column_labels;
var transpose = vaParameters._transpose_data;
if (!fileName) fileName = "DownloadedFromVA";
if (!showHeader) showHeader = "YES";
showHeader = (showHeader == 'YES');
if (!transpose) transpose = "NO";
transpose = (transpose == 'YES');
var csv = JSONToCSV(data, showHeader, transpose);
console.log("DOWNLOADING...");
DownloadCSV(csv, fileName);
console.log("DONE!");
}
</script>
</head>
<body>
<div>
<button class='gen_btn' onclick="download()">Download file</button>
</div>
</body>
</html>