Search code examples
sapui5

Upload TXT file and display data in SAPUI5 responsive table


I want to create a sap.m.Table in sapui5 in which the data’s in rows will be populated on uploading text file(.txt) which contains some details

For e.g.

Test.txt

1[tab]ABC Q

2[tab]PQR

3[tab]XYZ

In above text.txt,

1,2,3… are customer nos and ABC,PQR… are customer details. I wrote the logic for reading data from test.txt file on upload (refer below jsbin link example) and assigned data into multidimensional array as shown in below image

http://jsbin.com/fenexuqule/edit?html,output

multidimensional array value on inspect

When I upload the text file, I want to create a sap.m.table dynamically in which there will be 2 columns customer no and customer details and the data should be populated into their respective row.

Refer below table structure (Expected Table)

----------------------------------
| customer no | customer details |
----------------------------------
|         1   | ABC Q            |
|         2   | PQR              |
|         3   | XYZ              |

Thanking you in advance.


Solution

  • What I'd do...

    Convert your CSV to JSON and create a model object

    var aCSV = strCSV.split('\n'), row = {};
    
    for (var i = 0; i < aCSV.length; ++i) {
         row = aCSV[i].split(';');
         aCSV[i] = { 
             "cusno": row[0], 
             "cusdetail" : row[1]
         }
    }
    
    var oModel = new sap.ui.model.json.JSONModel(aCSV);
    

    Create your Table

    var oTable = new sap.m.Table({
        columns: [
            new sap.m.Column({
                header: new sap.m.Text({text: "Custom No"})
            }),
            new sap.m.Column({
                header: new sap.m.Text({text: "Customer Details"})
            })
        ]
    });
    
    oTable.placeAt("content");
    

    Bind data to your table

    oTable.setModel(oModel);
    
    oTable.bindAggregation("items", {
        path: "/", //json is an array of rows
        factory: function(sId, oContext) { //this function is applied to each row
            var cusno = new sap.m.Text({text: oContext.getProperty("cusno")});
            var cusdet = new sap.m.Text({text: oContext.getProperty("cusdetail")});
    
            return new sap.m.ColumnListItem({
                cells:[cusno, cusdet]
            });
        }
    });
    

    Full example: http://jsbin.com/tobifiqoto/2/edit?html,output