Hi guys,
I have a requirement to buildup a document from a template file(.DOTX), where I already have a table. You can see in the screenshot the structure of the table.
Here what I need is, to insert multiple rows or cells only in the particular columns which is Column C and Column D for my case.
I need to dynamically insert the rows in those two columns, keeping the formats intact.
can anybody Please help me out ?
image.png (2.4 KB)
@suprateembose In your case you need to use merged cells . You should use vertically merged cells to get the desired output.
The code like the following can be used to achieve what you need. It clones the row and vertically merges the cells in the cloned row. This is what MS Word does what you vertically split the cell.
Document doc = new Document(@"C:\temp\in.docx");
Table table = doc.FirstSection.Body.Tables[0];
SplitCellVertically(table.Rows[1].Cells[2], 5);
doc.Save(@"C:\Temp\out.docx");
private static void SplitCellVertically(Cell c, int cells)
{
// Get parent row of the cell.
Row parentRow = c.ParentRow;
// Get the cell index
int cellIndex = parentRow.Cells.IndexOf(c);
// Set vertical cell merge in the parent row.
// This row is the first.
foreach (Cell cell in parentRow.Cells)
{
if (cell != c)
cell.CellFormat.VerticalMerge = CellMerge.First;
}
// Clone and add the row below the parent row.
for (int i = 0; i < cells; i++)
{
Row r = (Row)parentRow.Clone(true);
// Merge cells with previouse.
foreach (Cell cell in r.Cells)
{
// Remove content from the cell
cell.RemoveAllChildren();
cell.EnsureMinimum();
if (r.Cells.IndexOf(cell) != cellIndex)
cell.CellFormat.VerticalMerge = CellMerge.Previous;
}
// Insert the cell below the parent cell
parentRow.ParentNode.InsertAfter(r, parentRow);
}
}