excel.js
1.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
const XLSX = require('xlsx-style');
function buildSheetFromMatrix(data, options) {
const workSheet = {};
data.forEach((cols, rowIndex) => {
cols.forEach((cell, colIndex) => {
const cellRef = XLSX.utils.encode_cell({ c: colIndex, r: rowIndex });
if (typeof cell === 'object' && cell) {
workSheet[cellRef] = cell;
} else {
workSheet[cellRef] = {
v: cell || ''
};
}
});
});
workSheet['!ref'] = XLSX.utils.encode_range({
s: { c: 0, r: 0 },
e: { c: data[0].length, r: data.length }
});
if (options.merges) {
workSheet['!merges'] = options.merges;
}
return workSheet;
}
module.exports.dataToExcel = (headers, datas) => {
const options = {
bookType: 'xlsx',
bookSST: false,
type: 'binary',
};
const workBook = {
SheetNames: ['sheet1'],
Sheets: {
sheet1: buildSheetFromMatrix(headers.concat(datas), options)
}
};
const excelData = XLSX.write(workBook, options);
return excelData instanceof Buffer ? excelData : Buffer.from(excelData, 'binary');
};