Export array to excel file with cell formatting

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

I start with this code here:

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

But the problem is that whenever I try to export it (saving the file as an xlsx file), this is an error that appears 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 two lines are mostly part of the code that says

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

I know wb is not undefined, as if I am trying to execute console.log, the excel spreadsheet is displayed correctly: |

Can someone help me? I also try to have each cell have a different formatting (IE different color / bold / filled / etc)

+7
javascript excel xlsx
source share
1 answer

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

Writing books

For recording, the first step is to create output. The helper functions write and writeFile will produce data in various formats suitable for distribution. The second step is the actual share of data with an endpoint. A prospective workbook is an object of a workbook:

write nodejs 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 a 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 summarize: you are trying to use the node.js internal functions in the browser, which fails. If you try to execute the seconds approach ( XLSX.write() instead of XLSX.writeFile() ), you should be fine.

+3
source share

All Articles