简体   繁体   中英

Add rows to a table dynamically in existing word document using OpenXml

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.

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.

My original word document: 加工前表的图片

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);
    }
}

Document after running code: 在此处输入图片说明

That should do the trick.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM