natergj / excel4node

Node module to allow for easy Excel file creation
MIT License
1.38k stars 215 forks source link

mergeCells function improvement #345

Open kenisad5566 opened 3 years ago

kenisad5566 commented 3 years ago

Describe the bug When hundreds of row need to merge, cell/index.js mergeCells function run slowly.

To Reproduce

const cells = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j","k", "l","m","n"]
for(let i = 0; i < 2000; i++){
    for(let j=0; j < cells.length; j++){
        workSheet.cell(
            i,
            j,
            i,
            j+1,
            true)
    }
}

render much more than hundreds of merge cell, it generate excel much more slowly.

Expected behavior It should be fast when render hundreds of merge cell excel.

Environment (please complete the following information):

Additional context In fact i have solved this problem for using the bundle source code with some change in my project temporarily. The function mergeCells run check merged cell every time, loop with all merged cell data, it seems cause to O(N2) time complexity for the check process.

this code cause to merge slow:

cellBlock.ws.mergedCells.forEach(function (cr) {
       // Check to see if currently merged cells contain cells in new merge request
       var curCells = utils.getAllCellsInExcelRange(cr);
       var intersection = utils.arrayIntersectSafe(rangeCells, curCells);
       if (intersection.length > 0) {
           okToMerge = false;
           cellBlock.ws.wb.logger.error('Invalid Range for: ' + cellRange + '. Some cells in this range are already included in another merged cell range: ' + cr + '.');
      }
});

My solution is :

// lib/cell/index.js  mergeCells
for (let site of rangeCells) {
   if (cellBlock.ws.mergedSites[site]) {
          okToMerge = false;
          cellBlock.ws.wb.logger.error(`Invalid Range for: ${cellRange}. Some cells in this range are already included in another 
               merged cell range: ${cr}.`);
          break
      }
 }
const time4 = new Date().getTime()
if (okToMerge) {
    cellBlock.ws.mergedCells.push(cellRange);
      for (let site of rangeCells) {
         cellBlock.ws.mergedSites[site] = 1
    }
}
// lib/worksheet/worksheet.js
this.mergedSites = {}; // add a map to store the mareged site