docs.sheetjs.com/docz/static/azure/index.js
2023-10-07 02:31:18 -04:00

38 lines
1.3 KiB
JavaScript

/* sheetjs (C) SheetJS -- https://sheetjs.com */
const { Blob } = require('buffer');
const { app } = require('@azure/functions');
const XLSX = require('xlsx');
app.http('SheetJSAzure', {
methods: ['GET', 'POST'],
authLevel: 'anonymous',
handler: async (req, context) => {
if (req.method == "POST") {
/* grab the file at form key `upload` */
const formData = await req.formData();
const f = formData.get("upload");
if (!f || !(f instanceof Blob)) {
return { status: 400, body: "Must submit a file for processing!" };
} else {
/* parse file */
const ab = await f.arrayBuffer();
const wb = XLSX.read(ab);
/* generate CSV from first sheet */
const csv = XLSX.utils.sheet_to_csv(wb.Sheets[wb.SheetNames[0]]);
return { status: 200, body: csv };
}
} else if (req.method == "GET") {
var ws = XLSX.utils.aoa_to_sheet(["SheetJS".split(""), [5, 4, 3, 3, 7, 9, 5]]);
var wb = XLSX.utils.book_new(); XLSX.utils.book_append_sheet(wb, ws, "Data");
var buf = XLSX.write(wb, { type: "buffer", bookType: "xlsx" });
return {
status: 200,
headers: { "Content-Disposition": `attachment; filename="SheetJSAzure.xlsx";` },
body: buf
};
} else return { status: 500, body: `Unsupported method ${req.method}` };
}
});