[英]Add rows to a table dynamically in existing word document using OpenXml
我正在使用OpenXml處理Word文檔。 現在,我的Word文檔(docx)寬度標題中有兩個表,現在我需要向這些表中添加動態行。
好吧,這應該對您有幫助。 我確定還有其他將行添加到現有表中的方法,但這是我使用的一種方法。
在此示例中,我假設您的表頭是1行。 在此示例中,我在Word的表中放置了一個名為“表”的書簽。 在表中的哪個位置都沒關系,因為我要遍歷“父母”,直到到達表。
帶有注釋的代碼進行解釋:
//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);
}
}
這應該夠了吧。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.