Is anyone able to tell me how I can make the following code generic please? I’m trying to insert a row from one file, into a table with a specified title under a specified bookmark in another file. I have attached sample files but in reality the number of tables present and the row number will be different between different files and unknown until runtime and I need this code to be able to handle any index they might be.
Here is the sample file with expected output:
ERROR_RowTest.zip (82.2 KB)
Here is my code, which works but will only handle the indexes in the sample files because the indexes are hardcoded:
InsertTableRow(@“c:\temp\Error_row.docx”, @“c:\temp\Error_table.docx”, “Bookmark2”, “Strawberry Delight”, @“c:\temp\Error_Output.docx”);
private static void InsertTableRow(string rowFilenameAndPath, string tableFilenameAndPath, string bookmarkName, string tableTitle, string outputFilenameAndPath)
{
Document tableDoc = new Document(tableFilenameAndPath);
Document rowDoc = new Document(rowFilenameAndPath);
NodeCollection tables = tableDoc.GetChildNodes(NodeType.Table, true);
Bookmark bm = tableDoc.Range.Bookmarks[bookmarkName];
Paragraph start = (Paragraph)bm.BookmarkStart.GetAncestor(NodeType.Paragraph);
Table targetTable = null;
CompositeNode node = (CompositeNode)start;
bool flag = true;
while (node != null && flag)
{
if (node.NodeType == NodeType.Table)
{
Table table = (Table)node;
if (table.Title == tableTitle)
{
targetTable = table;
flag = false;
break;
}
}
node = (CompositeNode)node.NextSibling;
}
if (targetTable != null)
{
NodeImporter imp = new NodeImporter(rowDoc, tableDoc, ImportFormatMode.KeepSourceFormatting);
Node impNode = imp.ImportNode(rowDoc.FirstSection.Body.Tables[0].Rows[0], true);
targetTable.Rows.Add(impNode);
}
tableDoc.Save(outputFilenameAndPath);
}