c# merging word's table colum's cells

35 Views Asked by At

I would like to merge cells from startRowIndex until startRowIndex+length. I am using Microsoft.Office.Interop.Word. For example:

Column 0 Column 1
Cell 1 Cell x
Cell 2 Cell x
Cell 3 Cell x
Cell 4 Cell x
Cell 5 Cell x
Cell 6 Cell x

My goal:

Column 0 Column 1
Cell 1 Cell x
Cell 1 Cell x
Cell 1 Cell x
Cell 2 Cell x
Cell 2 Cell x
Cell 2 Cell x

(as you can see i would like to skip the header row)

Here is my function i would like to use:

public void MergeUp(int firstCell = 1, int length = 2, int targetColumn = 0)

For this reason I would like to call this twice.

I tried many times, but I got exceptions like the cell is deleted, cannot merge multiple cells.

public void MergeUp(int firstCell = 1, int length = 2, int targetColumn = 0)
{
    if (firstCell < 1 || length < 2)
    {
        return;
    }
    if(Table.Rows.Count <3)
    {
        return;
    }

    for(int i = 0; i < length-1; i++)
    {
        var target = Table.Cell(firstCell, targetColumn);
        var current = Table.Cell(firstCell+1, targetColumn);
        target.Merge(current);
    }

}
0

There are 0 best solutions below