nodejs + jsxlsx use to download excel file stream

This article describes the file with Excel Node.js library is dependent, primarily using js-xlsx library file with Excel.

problem:

  1. Since the company official permission server received very tight, the site of linux account does not have write permission to use way to write the exported file excel, then query data using file streams exported.

  2. Because not familiar nodejs lead to an infinite stepped pit.

js-xlsx github address   https://github.com/SheetJS/sheetjs 

Because of the need to export excel file according to the document on github easiest way to display these additional restrictions if there is no similar privilege can be used to write files using writeFile way to export

If you have similar restrictions writeFile this way is not the best choice, after the query data, prepare the way the document flow for processing

jsxlsx also provides a very simple process, according to the document write my way to meet the need to set the type we need in write_opts, such as:

buf = Excel.write the let (WB, { 
type: 'Buffer',
bookType: 'XLSX'
})
before us we need to load the data to be exported as a worksheet:
let ws = Excel.utils.aoa_to_sheet (data); // data is our data 
the let Excel.utils.book_new WB = ();
Excel.utils.book_append_sheet (WB, WS, 'data XX');
After these steps then we export the work is essentially over, but do not forget because it is a way of using the appropriate settings file stream should add
ctx.set ( 'the Content-Disposition', 'Attachment; filename =' fileName +); 
ctx.type = "XLSX"
ctx.body = buf

distal upon receiving the file returned by the backend stream by corresponding treatment Blob :
const data = res.data;
const filename = res.headers['content-disposition'].split('=')[1]
// console.log(res.headers)
const url = window.URL.createObjectURL(
new Blob([data], {
type:
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
})
);
const link = document.createElement("a");
link.style.display = "none";
link.href = url;
link.setAttribute("download", filename);
document.body.appendChild(link);
link.click();
document.body.removeChild(link);

Guess you like

Origin www.cnblogs.com/cyworz/p/12023516.html