[SalesForce] Using xslx.js library on lightning component

I'm trying to use the xlsx.js library of cdnjs in a Lightning component. (https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.8.0/xlsx.js). I downloaded the js file and addit as an static resource but in the code when I try to use the XLSX object, always get an "undefined" error.

The resource always has the text/plain MIME Type, so I don't know if the problem is that SF cannot detect that is a java script file.

for the component I'm using the next syntaxis to get the file:

<ltng:require scripts="/resource/JsLibXlsx"
              afterScriptsLoaded="{!c.jsLoaded}"/>

in the controller just for verify the process I have this:

jsLoaded: function(component, event, helper) {
    alert('versiĆ³n 7');
    try{
        var xls = new XLSX();
        alert(xls);
    }
    catch(ex){
        alert(ex);
    }

}

alert shows

alert error
any ideas for this issue?

Thanks.

Best Answer

So, to make your XSLX library work, several things need to be done:

  1. Download XLSX.js - full library is more preferable, since you'll need to modify sources a bit.
  2. Open XLSX.js and right after the line

    var XLSX = {};

    (for me it was 5th line), add this line of code:

    window.XLSX = XLSX;

  3. Load modified library file as a static resource and reference it in your component as you would do with any other js library:

    <ltng:require scripts="{!$Resource.XLSX"}/>

  4. Library variable will be available in controller methods as XLSX. E.g.

    readFile: function (component, event) {
        var file = event.getSource().get("v.files")[0];
        var reader = new FileReader();
        reader.onloadend = function(e) {
            XLSX.read(e.target.result);
        };
        reader.readAsArrayBuffer(file);
    }
    

Explanation: by default, XLSX library inside the XLSX.js file is simply referenced as:

var XLSX = {};

In ordinary js this would be considered as a global variable, but lightning locker service encloses each library in a Proxy object, so that the library lives in it's own context. However, proxy object leaves direct references to window global context, if there were any. We simply explicitly order locker service to leave a reference to XLSX object in global window context for us.

Source: experience.

Additions: standard XLSX.js library doesn't include gzip library. So if you are not going to add it separately, you should modify and use xlsx.full.min.js. Basically, you should do the same thing as was described before, but for minified version of the library.

Related Topic