Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exporting an array to excel file with cell formatting

I'm currently trying to export an array to an excel file with cell formatting.

I'm starting off with this code here:

https://github.com/SheetJS/js-xlsx/blob/master/tests/write.js

But the problem is that whenever I'm trying to export it (save the file as an xlsx file) this is the error that shows up in the console:

Uncaught TypeError: Cannot read property 'writeFileSync' of undefined    xlsx.js:5182 
writeSync                 xlsx.js:5182 
writeFileSync             xlsx.js:5173 
process_xlsx              Test.html:379 
reader.onload             Test.html:438 

The last 2 lines are basically the part of the code which says

XLSX.writeFile(wb, 'sheetjs.xlsx');

I know wb is not undefined as if I try and do console.log of it, the excel spreadsheet shows up properly :|

Can someone help me with this? I'm also trying to have each cell have a different formatting (IE different color/bolded/filled/etc)

like image 668
Johnti Avatar asked Dec 18 '14 14:12

Johnti


1 Answers

You base your code on a node.js test. The documentation states:

Writing Workbooks

For writing, the first step is to generate output data. The helper functions write and writeFile will produce the data in various formats suitable for dissemination. The second step is to actual share the data with the end point. Assuming workbook is a workbook object:

nodejs write to file:

/* output format determined by filename */
XLSX.writeFile(workbook, 'out.xlsx');
/* at this point, out.xlsx is a file that you can distribute */

write to binary string (using FileSaver.js):

/* 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")

So to sum up: You try to use node.js internal functions in the browser, which fails. If you try to follow the seconds approach ( XLSX.write() instead of XLSX.writeFile()), you should be fine.

like image 196
Sirko Avatar answered Sep 28 '22 01:09

Sirko