node.jsxlsxexceljsnode.js-stream

How to style a XLSX file using exceljs and node.js streams?


Formatting and styling works in a typical situation

  const workbook = new ExcelJS.Workbook();
  const worksheet = workbook.addWorksheet('My Sheet');

  // Add headers
  worksheet.addRow(["Column 1", "Column 2", "Column 3", "Column 4"]).eachCell((cell) => {
    cell.fill = {
      type: 'pattern',
      pattern: 'solid',
      fgColor: { argb: '1a5896' }, // Yellow color
    };
    cell.font = { bold: true, color: { argb: 'F8F9FA' }, }; // Make text bold
  });

However while streaming a file to a HTTP response I am unable to change styling

  const workbook = new exceljs.stream.xlsx.WorkbookWriter({stream: response});
  const worksheet = workbook.addWorksheet('My Sheet');
  
  // Add headers
  worksheet.addRow(["Column 1", "Column 2", "Column 3", "Column 4"]).eachCell((cell) => {
    cell.fill = {
      type: 'pattern',
      pattern: 'solid',
      fgColor: { argb: '1a5896' }, // Yellow color
    };
    cell.font = { bold: true, color: { argb: 'F8F9FA' }, }; // Make text bold
  });

How can I change style of cells while streaming?


Solution

  • By default you can't add style information due to some performance overhead, you can override this behaviour by specifying useStyles set to true.

      const workbook = new exceljs.stream.xlsx.WorkbookWriter(
        { 
          stream: response,
          useStyles: true, // set this <-
        }
      );
      const worksheet = workbook.addWorksheet('My Sheet');
      
      // Add headers
      worksheet.addRow(["Column 1", "Column 2", "Column 3", "Column 4"]).eachCell((cell) => {
        cell.fill = {
          type: 'pattern',
          pattern: 'solid',
          fgColor: { argb: '1a5896' }, // Yellow color
        };
        cell.font = { bold: true, color: { argb: 'F8F9FA' }, }; // Make text bold
      });