3

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.

Nikola
  • 2,093
  • 3
  • 22
  • 43

1 Answers1

4

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);
Martin Choraine
  • 2,296
  • 3
  • 20
  • 37
  • 1
    You should probably prefer using the existing setter `alasql.setXLSX(XLSX)` – Gomino Oct 03 '19 at 17:42
  • 1
    It has been long since I was looking into this. Based on your explanation, I think you are probably right. I will set your answer as correct until/unless someone comes up with some good points why not. – Nikola Jun 10 '20 at 15:00