Search code examples
c#mergems-wordcellopenxml

How i can merge Microsoft Word table cells horizontally using OpenXML C#


I have a table in Microsoft Word. I need to merge two cells in a row of a table. I get the cells I need:

Wordprocessing.TableRow row = table.Elements<Wordprocessing.TableRow>().ElementAt(i);

 Wordprocessing.TableCell cell1 = row.Elements<Wordprocessing.TableCell>().ElementAt(j);

 Wordprocessing.TableCell cell2 = row.Elements<Wordprocessing.TableCell>().ElementAt(j+1);

How I can merge these cells horizontally?


Solution

  • You need to append a HorizontalMerge object to the cell's TableProperties.

    TableCellProperties cellOneProperties = new TableCellProperties();
    cellOneProperties.Append(new HorizontalMerge()
    {
        Val = MergedCellValues.Restart
    });
    
    TableCellProperties cellTwoProperties = new TableCellProperties();
    cellTwoProperties.Append(new HorizontalMerge()
    {
        Val = MergedCellValues.Continue
    });
    
    cell1.Append(cellOneProperties);
    cell2.Append(cellTwoProperties);