Search code examples
mysqlnode.jsexcelalasql

Node.JS: export data from mysql to excel using alasql


I'm writing a script to export data from mysql to excel using Node.JS and alasql. I can see examples in doing this.

var mystyle = {
  headers:true, 
  column: {style:{Font:{Bold:"1"}}},
  rows: {1:{style:{Font:{Color:"#FF0077"}}}},
  cells: {1:{1:{
    style: {Font:{Color:"#00FFFF"}}
  }}}
};
alasql('SELECT * INTO XLSXML("restest280b.xls",?) FROM ?',[mystyle,data]);

However, there is no documentation about what the variable data is and how I should construct it, particular in my case using recordset from mysql?

conn.query(SQL, function(err, rows, fields) {
    ALASQL('SELECT * INTO XLSXML("restest280b.xlsx",?) FROM ?',[mystyle,rows]); 
})

I tried to use mysql recordset directly. It wrote a file but can't be opened in excel.


Solution

  • Here data is a array or JSON objects, for example:

    var rows = [{a:1, b:10, c:'One'}, {a:2, b:20, c:'Two'} ];
    alasql('SELECT * INTO XLSXML("restest280b.xlsx",?) FROM ?',[mystyle,rows]); 
    

    If you use node-mysql package, your code should work.

    XLSXML() function generates XML file, and usually Windows version of MS Excel produce a warning. You can aliminate it if you will use XLSX() function with js-xlsx library:

    var rows = [{a:1, b:10, c:'One'}, {a:2, b:20, c:'Two'} ];
    alasql('SELECT * INTO XLSX("restest280b.xlsx") FROM ?',[rows]);