javascriptangularexceltypescriptexceljs

Iterate each cell with ExcelJS


I having trouble when I try to export an Excel with data al ready filled, this is the error message on console:

enter image description here

The total of results are 346880 with 28 headers that makes a total of 9,712,640 cells, and put so many console.log() too see better what's the real problema and end in this loop:

 headerRow.eachCell((cell, colNumber) => {
          cell.fill = { type: 'pattern', 
                        pattern: 'solid', 
                        fgColor: { argb: 'D9D9D9' } };
          cell.border = { top: { style: 'thin' }, 
                          left: { style: 'thin' }, 
                          bottom: { style: 'thin' }, 
                          right: { style: 'thin' } };
      
          const column = worksheet.getColumn(colNumber);
          const headerText = cell.text || '';
          const maxTextLength = Math.max(
            ...data.map(item => (item[colNumber - 1] || '').toString().length + headerText.length)
          );

          column.width = maxTextLength + 2;
        });

I try something like this:

const maxTextLengths [] = [];
for (let colNumber = 1; colNumber <= headerRow.cellCount; colNumber++) {
const headerText = headerRow.getCell(colNumber).text || '';
const maxLength = Math.max(
...data.map(item => (item[colNumber - 1] || '').toString().length + headerText.length)
);
maxTextLengths.push(maxLength);
}

headerRow.eachCell((cell, colNumber) => {
cell.fill = { type: 'pattern', pattern: 'solid', fgColor: { argb: 'D9D9D9' } };
cell.border = { top: { style: 'thin' }, left: { style: 'thin' }, bottom: { style: 'thin' }, right: { style: 'thin' } };

const column = worksheet.getColumn(colNumber);
column.width = maxTextLengths[colNumber - 1] + 2;
});

But got the same issue.


Solution

  • The problem is the call to Math.max(). It appears that you are looping through all 340,000+ rows which is causing the error. Instead of using Math.max(), get the longest cell length using something like:

    let maxLength = 0
    data.forEach(item => {
      const length = (item[colNumber - 1] || '').toString().length + headerText.length
      if (length > maxLength) {
        maxLength = length
      }
    })