我正在使用OpenXml處理Word文檔。現在我的文檔(docx)寬度標題中有兩個表格,現在我需要向這些表格添加動態行。使用OpenXml在現有Word文檔中動態添加行到表格
0
A
回答
1
好吧,這應該對你有幫助。我確信還有其他方法可以將行添加到現有表中,但這是我使用的方法。
我假設在這個例子中,你的表頭是exatcly 1行。在這個例子中,我在Word的表格裏放了一個名爲「table」的書籤。桌子上的哪個位置並不重要,因爲我正在通過Parent挖掘,直到我到達桌面。
代碼註釋解釋它:運行代碼後
//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);
}
}
這應該做的伎倆。
+0
我可以解決這個問題嗎?我怎樣才能直接訪問Word文檔中的表格? – Murad
+0
Table table = doc.MainDocumentPart.Document.Body.Elements
你到目前爲止嘗試過什麼? –
我還沒有嘗試過任何添加行,我不知道使用哪種方法。 – Murad