How to merge several cells into a single cell and split one cell into several cells in C#?

The table in a word document shows data and information clearly and it has been widely used. Sometimes, we need to merge several cells into a single one when a certain row requires a large space to record the text which span across the width of the table. We also need to split one cell into several cells for detail information.

This article will focus on introduce how to merge and split cells in a word table in C#. With the help of Spire.Doc, developers can merge cells and split cell easily and quickly by call the method ApplyHorizontalMerge(int rowIndex, int startCellIndex, int endCellIndex), ApplyVerticalMerge(int columnIndex, int startRowIndex, int endRowIndex) to merge multi-cells into one cell and TableCell.SplitCell(int columnNum, int rowNum) to split cells.

Firstly, download Spire.Doc (Version 5.1 or above) and install it on your system. Then adds Spire.Doc.dll as reference in the downloaded Bin folder though the below path: "..\Spire.Doc\Bin\NET4.0\ Spire.Doc.dll".

Here comes to the code snippet in C# how to merge and split table cell:

Step 1: Create a new word document

Document document = new Document();

Step 2: Add the first table

Section section = document.AddSection();
Table table1 = section.AddTable(true);
table1.ResetCells(4, 4);

Step 3: Merge several cells into one

table1.ApplyHorizontalMerge(0, 0, 3);
table1.ApplyHorizontalMerge(1, 2, 3);
table1.ApplyVerticalMerge(0, 2, 3);

Step 4: Add the second table

Table table2 = section.AddTable(true);
table2.ResetCells(4, 4);

Step 5: Split one cell into several cells.

table2.Rows[3].Cells[3].SplitCell(3, 2);

Step 6: Save the word document to file and process it.

document.SaveToFile("Sample.docx", FileFormat.Docx);
System.Diagnostics.Process.Start("Sample.docx");

Please check the effective screenshot:

Merge and Split table cell

Full codes:

Document document = new Document();
Section section = document.AddSection();
Table table1 = section.AddTable(true);
table1.ResetCells(4, 4);
table1.ApplyHorizontalMerge(0, 0, 3);
table1.ApplyHorizontalMerge(1, 2, 3);
table1.ApplyVerticalMerge(0, 2, 3);
section.AddParagraph();
Table table2 = section.AddTable(true);
table2.ResetCells(4, 4);
table2.Rows[3].Cells[3].SplitCell(3, 2);
document.SaveToFile("Sample.docx", FileFormat.Docx);
System.Diagnostics.Process.Start("Sample.docx");