I'm using OpenXml for working with word documents. Now I have two tables in my word document (docx) width headers, now I need to add dynamic rows to these tables.
1 Answer
Alright this should help you. I'm sure there are other ways of adding rows to an existing table, but this is the one I use.
I'm assuming in this example, that your table header is exatcly 1 row. And in this example I've put a bookmark called "table" inside my table in Word. It doesn't really matter where in the table, seeing as I'm digging out through Parent until I arrive at the table.
Code with comments explaining it:
//setup
using (var wordDoc = WordprocessingDocument.Open(@"C:\test\cb\exptable.docx", true))
{
MainDocumentPart mainPart = wordDoc.MainDocumentPart;
var document = mainPart.Document;
var bookmarks = document.Body.Descendants<BookmarkStart>();
//find bookmark
var myBookmark = bookmarks.First(bms => bms.Name == "table");
//dig through parent until we hit a table
var digForTable = myBookmark.Parent;
while(!(digForTable is Table))
{
digForTable = digForTable.Parent;
}
//get rows
var rows = digForTable.Descendants<TableRow>().ToList();
//remember you have a header, so keep row 1, clone row 2 (our template for dynamic entry)
var myRow = (TableRow)rows.Last().Clone();
//remove it after cloning.
rows.Last().Remove();
//do stuf with your row and insert it in the table
for (int i = 0; i < 10; i++)
{
//clone our "reference row"
var rowToInsert = (TableRow)myRow.Clone();
//get list of cells
var listOfCellsInRow = rowToInsert.Descendants<TableCell>().ToList();
//just replace every bit of text in cells with row-number for this example
foreach(TableCell cell in listOfCellsInRow)
{
cell.Descendants<Text>().FirstOrDefault().Text = i.ToString();
}
//add new row to table, after last row in table
digForTable.Descendants<TableRow>().Last().InsertAfterSelf(rowToInsert);
}
}
That should do the trick.
3 Comments
Murad
Can i solve this problem without any trick? And How can i directly access to table inside word document?
Murad
Table table = doc.MainDocumentPart.Document.Body.Elements<Table>().First(); this code snippet finds the first table inside word document, using this way i can find second, third tables, can't i?
Kaspar Kjeldsen
... Yes ? I'm not entirely sure what you are asking, could you use my answer? Yes, you can use your code snippet to find the first table, given that it is a child of Body. If it is inside a paragraph or something else, and not a direct child, you can use Descendants<Table>, like I do in my example.

