Skip to Content

Hello All,

‘CSV’ is a simple format used to store tabular data, such as spreadsheet or database. Data in the CSV format can be imported.

Now, in our case we have the data placed in CSV format. Using sap.ui.unified.Uploader, we can upload ‘CSV’ document and has an ability to restrict the file type using ‘setFileType’ method.

Once the document is uploaded, we can convert it to JSON format by parsing through CSV data and store the JSON data into a model.


        handleUpload: function(oEvent) {
          var that = this;
          var oFile = oEvent.getParameter("files")[0];
          if (oFile && window.FileReader) {
            var reader = new FileReader();
            reader.onload = function(evt) {
              var strCSV = evt.target.result; //string in CSV
              that.csvJSON(strCSV);
            };
            reader.readAsText(oFile);
          }
        },
        csvJSON: function(csv) {
          var lines = csv.split("\n");
          var result = [];
          var headers = lines[0].split(",");
          for (var i = 1; i < lines.length; i++) {
            var obj = {};
            var currentline = lines[i].split(",");
            for (var j = 0; j < headers.length; j++) {
              obj[headers[j]] = currentline[j];
            }
            result.push(obj);
          }
          var oStringResult = JSON.stringify(result);
          var oFinalResult = JSON.parse(oStringResult.replace(/\\r/g, ""));
          //return result; //JavaScript object
          sap.ui.getCore().getModel().setProperty("/", oFinalResult);
          this.generateTable();
        }

From above code Table data is ready. Now, we will have to fetch the column name labels. To fetch key names from model, we can use following method:


          var oModel = sap.ui.getCore().getModel();
          var oModelData = oModel.getProperty("/");
          var oColumns = Object.keys(oModelData[0]);

Store the key names into different property on same model and create the template that need to be used for ‘columns’ aggregation.


          var oColumnNames = [];
          $.each(oColumns, function(i, value) {
            oColumnNames.push({
              Text: oColumns[i]
            });
          });
          oModel.setProperty("/columnNames", oColumnNames);
          var oTemplate = new Column({
            header: new Label({
              text: "{Text}"
            })
          });

For ‘items’ aggregation we can use the default binding path which has data and create the template that need to be used:


          var oItemTemplate = new ColumnListItem();
          var oTableHeaders = oTable.getColumns();
          $.each(oTableHeaders, function(j, value) {
            var oHeaderName = oTableHeaders[j].getHeader().getText();
            oItemTemplate.addCell(new Text({
              text: "{" + oHeaderName + "}"
            }));
          });

Now getting it to all together, bind ‘columns’ / ‘items’ aggregation with respective binding paths and templates.

Finally, table gets generated based on CSV data. In result, no need to re-code if you want to use different CSV documents. You can just upload and read it.

Full working demo of Dynamic Table creation based on CSV data: Plunker

Working Snip:

Capture.gif

Thanks for reading my blog, have a great day.


Regards,

Sai Vellanki.

To report this post you need to login first.

2 Comments

You must be Logged on to comment or reply to a post.

  1. Sonja Deißenböck

    This is a great blog post and I feel like I’m close to achieving what you’re describing. But somehow there is one little part missing and I can’T find it. Could you maybe help me?? Here’s my code:

    handleUpload: function(oEvent) {
    var that = this;
    var oFile = oEvent.getParameter(“files”)[0];
    if (oFile && window.FileReader) {
    var reader = new FileReader();
    reader.onload = function(evt) {
    var strCSV = evt.target.result; //string in CSV
    that.csvJSON(strCSV);
    };
    reader.readAsText(oFile);
    }
    },
    csvJSON: function(csv) {
    var lines = csv.split(“\n”);
    var result = [];
    var headers = lines[0].split(“,”);
    for (var i = 1; i < lines.length; i++) {
    var obj = {};
    var currentline = lines[i].split(“,”);
    for (var j = 0; j < headers.length; j++) {
    obj[headers[j]] = currentline[j];
    }
    result.push(obj);
    }
    var oStringResult = JSON.stringify(result);
    var oFinalResult = JSON.parse(oStringResult.replace(/\\r/g, “”));
    //return result; //JavaScript object

    this.getView().getModel(‘myResultModel’).setProperty(“/”, oFinalResult);
    this.generateTable();
    },

    generateTable: function() {
    var oTable = this.getView().byId(“testdata”);
    var oModel = this.getView().getModel(‘myResultModel’)
    var oModelData = oModel.getProperty(“/”);
    var oColumns = Object.keys(oModelData[0]);
    var oColumnNames = [];
    $.each(oColumns, function(i, value) {
    oColumnNames.push({
    Text: oColumns[i]
    });
    });
    oModel.setProperty(“/columnNames”, oColumnNames);
    var oTemplate = new Column({
    header: new Label({
    text: “{Text}”
    })
    });
    oTable.bindAggregation(“columns”, “/columnNames”, oTemplate);
    var oItemTemplate = new ColumnListItem();
    var oTableHeaders = oTable.getColumns();
    $.each(oTableHeaders, function(j, value) {
    var oHeaderName = oTableHeaders[j].getHeader().getText();
    oItemTemplate.addCell(new Text({
    text: “{” + oHeaderName + “}”
    }));
    });
    oTable.bindItems(“/”, oItemTemplate);
    },

    after uploading, my table stays empty for some reason..

    I tiple checked your code and would be so greatful for any advice!

    (0) 

Leave a Reply