Converting Excel to JSON SAPUI5

1.8k Views Asked by At

I'm using SAPUI5 and I'm trying to upload an Excel and, using the XLSX-JS library, convert it into a JSON, so I can read it and show into a table.

Here is the link to the github library project:

https://github.com/SheetJS/js-xlsx

I'm having few troubles doing that, so I need to know what I'm doing wrong...

I'm using the WEB IDE application, and I tried to do the upload and then read the file, but doesn't work, so I decided, manually, import the excel (to try if i can read these from a path), and still not working.

Here is what I'm using to read the file I imported manually:

sap.ui.define([
    "sap/ui/core/mvc/Controller",
    "sap/m/MessageToast",
    "ExcelImport/ExcelImport/libs/xlsx.full.min"
], function (Controller, MessageToast, XLSX) {
    "use strict";

    return Controller.extend("ExcelImport.ExcelImport.controller.ExcelImportView", {
        onInit: function () {

            var oModel = new sap.ui.model.json.JSONModel();
            this.getView().setModel(oModel);
            sap.ui.getCore().setModel(oModel);

        },

        handleExcelUpload: function () {

            var url = "/files/TRY.xlsx";

            /* set up async GET request */
            var req = new XMLHttpRequest();
            req.open("GET", url, true);
            req.responseType = "arraybuffer";

            req.onload = function (e) {
                var data = new Uint8Array(req.response);
                var workbook = XLSX.read(data, {
                    type: "array"
                });

                /* DO SOMETHING WITH workbook HERE */
                var first_sheet_name = workbook.SheetNames[0];

                /* Get worksheet */
                var worksheet = workbook.Sheets[first_sheet_name];
                MessageToast.show(XLSX.utils.sheet_to_json(worksheet));

            };

            req.send();
        }
    });
});

First of all, I'm having an error with the Uint8Array, which is not defined. After that, when I press the button that calls handleExcelUpload, it shows me the following error:

TypeError: Cannot read property 'read' of undefined
    at XMLHttpRequest.req.onload (ExcelImportView.controller.js:46)

For now, the output I'm expecting it's just to show the JSON via a MessageToast, because, once I have the JSON, would be so easy to send into a table.

I think if I can get through this problem with an pre-imported file, I could solve the problem with the import too.

Don't know if the problem is with the Uint8Array, or with something else... help please!!


EDIT:

Still looking for an answer, didn't found a solution yet


Thanks!

0

There are 0 best solutions below