Automatically detect and merge cells in table

Deark Aspose
Thanks for your amazing product.

I was wondering if there is a way to vertically merge columns with the same value.
I know that I can use builder.CellFormat.VerticalMerge = CellMerge.First; to start the merge process but in this case, I have to programmatically check the value of the same column to the corresponding column in the previous row and check whether it has changed or not.

How can automatically detect and merge cells with the same value in Aspose Words?
Let me elaborate more, Consider the following table that is generated dynamically.

Col1     Col2    Col3    Col4
aaa1     bbb1    ccc1    ddd1   
aaa2     bbb1    ccc2    ddd1   
aaa3     bbb2    ccc3    ddd1   
aaa4     bbb2    ccc3    ddd1  

I want all bbb1 merged together and the same happen for bbb2, ccc3 and ddd1. Generally speaking for all columns with the same value.

Thanks in advance.

@mohammad19i Unfortunately, there is no way to automatically merge cells with the same values. You can achieve this using code like the following:

Document doc = new Document(@"C:\Temp\in.docx");

// Get the table.
Table table = doc.FirstSection.Body.Tables[0];

for (int rowIdx = 0; rowIdx < table.Rows.Count - 1; rowIdx++)
{
    Row currentRow = table.Rows[rowIdx];
    Row nextRow = table.Rows[rowIdx + 1];

    // Assume all rows have the same number of cells.
    for (int cellIdx = 0; cellIdx < currentRow.Cells.Count; cellIdx++)
    {
        Cell currentCell = currentRow.Cells[cellIdx];
        Cell nextCell = nextRow.Cells[cellIdx];
        // Vertically merge cells with the same values.
        if (currentCell.GetText() == nextCell.GetText())
        {
            if (currentCell.CellFormat.VerticalMerge == CellMerge.None)
                currentCell.CellFormat.VerticalMerge = CellMerge.First;

            nextCell.CellFormat.VerticalMerge = CellMerge.Previous;
        }
    }
}

doc.Save(@"C:\Temp\out.docx");

in.docx (13.1 KB)
out.docx (10.4 KB)

1 Like