question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

[BUG] addRow() not adding merged cells correctly which are read from source file

See original GitHub issue

Hi All,

I am trying to read from a excel file, manipulate some data and write to another excel. I am seeing a weird issue when adding rows which have merged cells. They are not getting added as expected in the destination file, the rows are appearing non-merged.

Below is the relevant part of the code. I am using streams and addRow.

const readerOptions = {
sharedStrings: 'cache',
 hyperlinks: 'cache',
 worksheets: 'emit',
 styles: 'cache',
};
const writerOptions = {
 filename: fpath,
 useStyles: true,
 useSharedStrings: true
}
const workbook = new ExcelJS.stream.xlsx.WorkbookWriter(writerOptions)
const myworksheet = workbook.addWorksheet('Sheet 1');
const workbookReader = new ExcelJS.stream.xlsx.WorkbookReader(sheet.path, readerOptions);
workbookReader.read();
workbookReader.on('worksheet', worksheet => {
 worksheet.on('row', row => {
  const r = myworksheet.addRow();
  Object.assign(r, row);
 });
});

workbookReader.on('end', async () => {
 await workbook.commit();
});

Please find the below images for your reference. first image is actual_result.png and second image is expected_result.png

actual_result expected_result

Any help on how to fix this will be really great, Thanks.

Issue Analytics

  • State:open
  • Created 3 years ago
  • Comments:9 (2 by maintainers)

github_iconTop GitHub Comments

2reactions
eug-vscommented, Mar 17, 2021

Hi! Could this be related to #292? My use-case is duplicating rows: currently duplicating a row with merged cells results into a row with all cells unmerged. I’ve came up with a workaround (it assumes that row you’re duplicating only contains merged cells within itself, i.e no cell in this row is merged with other rows):

const duplicateRowWithMergedCells = (sheet: any, row: number, count: number) => {
  sheet.duplicateRow(row, count, true);

  const merges: string[] = sheet.model.merges;
  // Find all merges inside initial row
  const rowMerges = merges.filter(range => range.match(`\\w+${row}:\\w+${row}`));

  _.times(count, index => {
    const newRow = row + index + 1;

    // Unmerge everything in a newRow so we dont run into conflicts
    merges
      .filter(range => range.match(`\\w+${newRow}:\\w+${newRow}`))
      .forEach(range => sheet.unMergeCells(range));

    // Merge the same cells as in the initial row
    rowMerges
      .map(range => range.replace(new RegExp(`${row}`, 'g'), `${newRow}`))
      .forEach(range => sheet.mergeCells(range));
  });
};

Do you think the above way makes sense or may be there might be a better way to detect if rows has merged cells.

@aksharj note how I unmerge rows before manually transferring new merges. I think this answers you question.

I did not dive deep into the library, but my understanding of this part of the bug is: when duplicating a row with insert = true (and maybe in other scenarios) it does not remove old merges from cells which were previously on the positions where are you inserting. Therefore you can run into conflicts sometimes.

1reaction
aksharjcommented, Dec 18, 2020

hi @Siemienik thanks for your reply. Actually, excel files in some case might be large that’s the reason i need to use streams.

I have found a workaround, i am checking if the row has merged cells and then merge it again after adding rows. The way i am checking if rows contain merged cells is as follows.

if((newRow.actualCellCount !== newRow.cellCount) && (newRow.actualCellCount == 1)) {

Do you think the above way makes sense or may be there might be a better way to detect if rows has merged cells.

Full relevant code to copy excel is as follows.

        const workbook = new ExcelJS.stream.xlsx.WorkbookWriter(writerOptions);
        const workbookReader = new ExcelJS.stream.xlsx.WorkbookReader(sheet.path, readerOptions);
        const myworksheet = workbook.addWorksheet('Sheet 1');
        workbookReader.read();
        workbookReader.on('worksheet', worksheet => {
          worksheet.on('row', row => {
            const newRow = myworksheet.addRow();
            Object.assign(newRow, row);
            if((newRow.actualCellCount !== newRow.cellCount) && (newRow.actualCellCount == 1)) {
              let cellLength = newRow.model.cells.length;
              myworksheet.mergeCells(`${newRow.model.cells[0].address}:${newRow.model.cells[cellLength - 1].address}`)
            }
          });
        });

Do let me know if this makes sense or may be better way to achieve this, for now this works for me.

Thanks.

Read more comments on GitHub >

github_iconTop Results From Across the Web

POI Word Unable to merge newly created cell vertically
The problem you have is not with mergeCellVertically method but with your approach to copy table row. When copying the underlying CTRow and ......
Read more >
We can't do that to a merged cell. - Microsoft Tech Community
Hi, I am trying to copy a file that filtered in column J and merged some cells. The windows has shown a error...
Read more >
92960 – Calc doesn't merge cells correctly when pasting ...
Well seems that the issue is pasting (not the same than inserting) from HTML into a spreadsheet. For me the issue happens not...
Read more >
4.3.0 - exceljs - npm
Excel Workbook Manager - Read and Write xlsx and csv Files. ... Add Rows; Handling Individual Cells; Merged Cells; Insert Rows; Splice ...
Read more >
FlexCel API Developer Guide
Column C has XF = 1, so all the empty cells on column C that do not have a Row ... So if...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found