Search code examples
javascriptexceljs-xlsx

Error when use a library - javascript


I use js-xlsx library. I need to write an excel file. So when I defined a wb variable as excel workbook and asked js-xlsx to write it to same file

XLSX.writeFile(wb, 'out.xls');

I get an error at browser console:

require.js:900 TypeError: Cannot read property 'writeFileSync' of undefined

XLSX.writeFile turns to js-xlsx/dist/xlsx.js row 1340

_fs = require('f'+'s');

And when I paused it to debug, _fs is undefined, of cource. I can't see where I could find 'f' or 's' libs. Please help me to understand it.


Solution

  • try using XLSX.write-- writeFile function is specific to nodejs


    • XLSX.write(wb, filename) write to binary string (->browser)

    • XLSX.writeFile(wb, filename) nodeJS function


    /* XLSX.write(wb, 'out.xls'); */
    
    /* bookType can be 'xlsx' or 'xlsm' or 'xlsb' */
    var wopts = { bookType:'xlsx', bookSST:false, type:'binary' };
    
    var wbout = XLSX.write(workbook,wopts);
    
    function s2ab(s) {
      var buf = new ArrayBuffer(s.length);
      var view = new Uint8Array(buf);
      for (var i=0; i!=s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
      return buf;
    }
    
    /* the saveAs call downloads a file on the local machine */
    saveAs(new Blob([s2ab(wbout)],{type:""}), "test.xlsx")
    

    https://github.com/SheetJS/js-xlsx#user-content-writing-workbooks