excel.js 1.06 KB
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');
};