Skip to content

Commit 72b1269

Browse files
author
Barry Dam
committed
[Added] exportToCSV method
1 parent dd7e2cf commit 72b1269

File tree

2 files changed

+157
-6
lines changed

2 files changed

+157
-6
lines changed

CRUDModel.js

Lines changed: 93 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -11,9 +11,13 @@
1111
jQuery.sap.declare('nl.barrydam.model.CRUDModel');
1212
jQuery.sap.require("jquery.sap.storage");
1313
sap.ui.define(
14-
'nl/barrydam/model/CRUDModel',
15-
['sap/ui/model/json/JSONModel'],
16-
function(JSONModel) {
14+
"nl/barrydam/model/CRUDModel",
15+
[
16+
"sap/ui/model/json/JSONModel",
17+
"sap/ui/core/util/Export",
18+
"sap/ui/core/util/ExportTypeCSV",
19+
],
20+
function(JSONModel, Export, ExportTypeCSV) {
1721
"use strict";
1822

1923

@@ -405,7 +409,7 @@
405409
case "date":
406410
case "datetime":
407411
case "timestamp":
408-
sValue = new Date(sValue);
412+
sValue = (! sValue || sValue == "0000-00-00") ? null : new Date(sValue) ;
409413
break;
410414
default: // nothing
411415
break;
@@ -1180,6 +1184,89 @@
11801184
return id;
11811185
};
11821186

1187+
/**
1188+
* Export to CSV
1189+
* @param string sPath path
1190+
* @param map mParameters [description]
1191+
* @return
1192+
*/
1193+
CRUDModel.prototype.exportToCSV = function(sPath, mParameters) {
1194+
var mPath = _methods.parsePath(sPath);
1195+
mParameters = (typeof mParameters === "object") ? mParameters : {} ;
1196+
mParameters.error = ("error" in mParameters && typeof mParameters.error === "function") ? mParameters.error : function() {} ;
1197+
mParameters.excludeColumns = ("excludeColumns" in mParameters && $.isArray(mParameters.excludeColumns)) ? mParameters.excludeColumns : "[]" ;
1198+
mParameters.filename = ("filename" in mParameters) ? mParameters.filename : mPath.Table+"-"+Date.now() ;
1199+
mParameters.formatValue = ("formatValue" in mParameters && typeof mParameters.formatValue === "function") ? mParameters.formatValue : function(sColumn, sValue) { return sValue; } ;
1200+
mParameters.formatColumnName = ("formatColumnName" in mParameters && typeof mParameters.formatColumnName === "function") ? mParameters.formatColumnName : function(sName) { return sName; } ;
1201+
mParameters.includeColumns = ("includeColumns" in mParameters) ? mParameters.includeColumns : null ; // , = ui5 default
1202+
mParameters.refreshData = ("refreshData" in mParameters) ? mParameters.refreshData : false ; // , = ui5 default
1203+
mParameters.separatorChar = ("separatorChar" in mParameters) ? mParameters.separatorChar : "," ; // , = ui5 default
1204+
mParameters.success = ("success" in mParameters && typeof mParameters.success === "function") ? mParameters.success : function() {} ;
1205+
// check if path has set
1206+
if (! mPath.Table) {
1207+
return mParameters.error("\"sPath\" is undefined", "error");
1208+
}
1209+
if (mParameters.refreshData || ! this.getProperty("/"+mPath.Table)) {
1210+
this.read(mPath.Table, {
1211+
success: function(mData) {
1212+
_methods.exportToCSV(mData, mParameters);
1213+
},
1214+
error: function() {
1215+
return mParameters.error("\"sPath\" is undefined", "error");
1216+
}
1217+
});
1218+
} else {
1219+
_methods.exportToCSV(this.getProperty("/"+mPath.Table), mParameters);
1220+
}
1221+
};
1222+
_methods.exportToCSV = function(m, mParameters) {
1223+
if (Object.keys(m).length === 0) {
1224+
mParameters.error("no data", "no_data");
1225+
return;
1226+
}
1227+
var aColumns = [],
1228+
aData = [];
1229+
for (var i in m) {
1230+
// create the columns
1231+
if (aColumns.length === 0) {
1232+
aColumns = Object.keys(m[i]);
1233+
if (mParameters.excludeColumns.length !== 0) {
1234+
aColumns = aColumns.filter(function(sWord) { return (mParameters.excludeColumns.indexOf(sWord) === -1); });
1235+
}
1236+
if (mParameters.includeColumns.length !== 0) {
1237+
aColumns = aColumns.filter(function(sWord) { return (mParameters.includeColumns.indexOf(sWord) !== -1); });
1238+
}
1239+
aColumns = aColumns.map(function(sColumn) {
1240+
return {
1241+
name : mParameters.formatColumnName(sColumn),
1242+
template : { content: "{"+sColumn+"}" }
1243+
};
1244+
});
1245+
}
1246+
// format the value
1247+
for (var sColumn in m[i]) {
1248+
m[i][sColumn] = mParameters.formatValue(sColumn, m[i][sColumn]);
1249+
}
1250+
// add to csv data
1251+
aData.push(m[i]);
1252+
}
1253+
var oExport = new Export({
1254+
exportType : new ExportTypeCSV({
1255+
separatorChar : mParameters.separatorChar
1256+
}),
1257+
models : new JSONModel(aData),
1258+
rows : { path : "/" },
1259+
columns : aColumns
1260+
});
1261+
oExport.saveFile(mParameters.filename)
1262+
.catch(function() {
1263+
mParameters.error(error, "compile_error");
1264+
}).then(function(error){
1265+
mParameters.success();
1266+
oExport.destroy();
1267+
});
1268+
};
1269+
11831270

11841271
/**
11851272
* Checks if there exist pending changes in the model created by the setProperty method.
@@ -1843,6 +1930,8 @@
18431930
return _variables.csrf;
18441931
};
18451932

1933+
1934+
18461935
return CRUDModel;
18471936

18481937
},

README.md

Lines changed: 64 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -90,9 +90,10 @@ oServiceExample.attachLogin(function() {
9090

9191
[callFunction](#callFunction),
9292
[clearBatch](#clearBatch),
93-
[create](#createspath-odata-mparmeters),
93+
[create](#createspath-odata-mparameters),
9494
[createBatchOperation](#createbatchoperationspath-smethod-odata),
9595
[createEntry](#createentryspath-odata),
96+
[exporToCSV](#exporttocsvspath-mparamenters),
9697
[getPrimaryKey](#getprimarykeystablename),
9798
[hasPendingChanges](#hasPendingChanges),
9899
[login](#loginsuser-spassword-mparameters),
@@ -116,7 +117,7 @@ Trigger a request to the function import OData service that was specified in the
116117
Removes all operations in the current batch.
117118

118119

119-
### create(sPath, oData, mParmeters?)
120+
### create(sPath, oData, mparameters?)
120121
Trigger a POST request to the CRUD service that was specified in the model constructor. Please note that deep creates are not supported and may not work.
121122

122123
**Parameters:**
@@ -163,6 +164,67 @@ Type | Variable | Description
163164
*{string}* | **sPath** | Name of the path to the collection.
164165
*{object}* | **oData** | An object that specifies a set of properties or the entry
165166

167+
### exportToCSV(sPath, oData, mparameters?)
168+
Export the data to a CSV file.
169+
170+
**Parameters:**
171+
172+
Type | Variable | Description
173+
--- | --- | ---
174+
*{string}* | **sPath** | A string containing the path to the collection where an entry should be created. The path is concatenated to the sServiceUrl which was specified in the model constructor.
175+
*{object}* | **oData** | Data of the entry that should be created.
176+
*{map}* | **mParameters?** | Optional parameter map containing any of the following properties:
177+
*{function}* | **mParameters.success?** | A callback function which is called when the data has been successfully retrieved. The handler can have the following parameters: oData and response.created.
178+
*{function}* | **mParameters.error?** | A callback function which is called when the request failed. The handler can have the parameter oError which contains additional error information.
179+
*{array}* | **mParameters.excludeColumns?** | Array of columns which should be excluded in the CVS export, default false (no columns will be excluded)
180+
*{string}* | **mParameters.filename?** | Filename for the CSV file. If not set, the filename is generated by combining the sPath + the current timestamp
181+
*{function}* | **mParameters.formatValue?** | A callback function which is called when each value is parsed. return the value you want to show in the CSV row.* The handler has the following parameters (string) sColumn and (mixed) value (*see example below)
182+
*{function}* | **mParameters.formatColumnName?** | A callback function which is called on creating the CSV header columns. return the columnname you would like tho show in the first csv row.* The handler has the following parameter (string) sName. (*see example below)
183+
*{array}* | **mParameters.includeColumns?** | Array of columns which should only be included in the CSV export, default false (all columns will be included)
184+
*{boolean}* | **mParameters.refreshData?** | If set to True, a fresh set of data will be requested. If set to false, the current model data would be used (if there is no data available a new request will be fired towards the api), default false
185+
*{string}* | **mParameters.separatorChar?** | default: ,
186+
187+
```js
188+
/*
189+
This example below will result in a my-custom-filename.csv download
190+
*/
191+
API.exportToCSV('example', {
192+
error: function(sMessage, sType) {
193+
if (sType == "no_data") {
194+
alert("No data available")
195+
} else {
196+
alert("Error creating export file");
197+
}
198+
oBtn.setBusy(false);
199+
},
200+
separatorChar : ";",,
201+
filename : "my-custom-filename",
202+
formatValue: function(sColumn, sValue) {
203+
switch (sColumn) {
204+
case "birthDate":
205+
sValue = (sValue) ? moment(sDate).format("LL") : "" ;
206+
break;
207+
case "temporary":
208+
sValue = (sValue=== 0) ? "No" : "Yes" ;
209+
break;
210+
}
211+
return sValue;
212+
},
213+
formatColumnName: function(sName) {
214+
switch (sName) {
215+
case "birthDate":
216+
sName = "Birth Date"
217+
break;
218+
219+
case "temporary":
220+
sName = "Only temporary?"
221+
break;
222+
}
223+
return sName;
224+
}
225+
});
226+
```
227+
166228

167229
### getPrimaryKey(sTablename?)
168230
Get the table primary key. If there is no primary key set in the db, it will return the default primary key which is 'id', the default primaryKey can be changed by setPrimaryKey(); or by passing primaryKey in the class constructor

0 commit comments

Comments
 (0)