excelxlsxalasqljs-xlsx

alasql requires xlsx which is already included


I am trying to export data to an excel sheet using alasql and xlsx. I have followed all the guidelines here: https://github.com/agershun/alasql/wiki/Xlsx

This is my function:

exportToExcel(data: any) {
   console.log(XLSX.version);

   alasql
     .promise('SELECT * INTO XLSX("test.csv",{headers:true}) FROM ?', [data])
     .then(function (data) { console.log(data); })
     .catch(function (err) { console.log('Error:', err); });;
}

which gives me this error in my console together with the XLSX version:

VM9931 main.bundle.js:1044 0.12.4 VM9931 main.bundle.js:1047 Error: Error: Please include the xlsx.js library at B (VM9930 vendor.bundle.js:6298) at Object.A.into.XLSX (VM9930 vendor.bundle.js:6303)

The problem I am experiencing is that I have already included the XLSX library and it's working correctly (the version logged is 0.12.4). If I change the XLSX("test.csv")... to CSV("test.csv")... it exports to CSV perfectly.


Solution

  • After reading source code from alasql, I looked closely on the part which get XLSX :

    var getXLSX = function() {
    var XLSX = alasql["private"].externalXlsxLib;
    
      if (XLSX) {
        return XLSX;
      }
    
      if (utils.isNode || utils.isBrowserify || utils.isMeteorServer) {
        /*not-for-browser/*
        XLSX = require('xlsx') || null;
        //*/
      } else {
        XLSX = utils.global.XLSX || null;
      }
    
      if (null === XLSX) {
        throw new Error('Please include the xlsx.js library');
      }
    
      return XLSX;
    
    };
    

    I don't know exactly why but line XLSX = require('xlsx') || null is commented so you need to explicitly set externalXlsxLib to use xlsx :

    import * as alasql from 'alasql';
    alasql["private"].externalXlsxLib = require('xlsx');
    

    Update

    As suggested in comment there is now a setter function that you can use to provide xlsx. You should definitely use this cleaner approach.

    import * as alasql from 'alasql';
    var XLSX = require('xlsx')
    alasql.setXLSX(XLSX);