2017-04-26 126 views

回答

1

好吧,這應該對你有幫助。我確信還有其他方法可以將行添加到現有表中,但這是我使用的方法。

我假設在這個例子中,你的表頭是exatcly 1行。在這個例子中,我在Word的表格裏放了一個名爲「table」的書籤。桌子上的哪個位置並不重要,因爲我正在通過Parent挖掘,直到我到達桌面。

我原來的word文檔: picture of table before processing

代碼註釋解釋它:運行代碼後

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

文件: enter image description here

這應該做的伎倆。

+0

我可以解決這個問題嗎?我怎樣才能直接訪問Word文檔中的表格? – Murad

+0

Table table = doc.MainDocumentPart.Document.Body.Elements

().First();這段代碼片段找到word文檔中的第一個表格,使用這種方式我可以找到第二個,第三個表格,不是嗎? – Murad

+0

...是的?我不完全確定你在問什麼,你能用我的答案嗎?是的,你可以使用你的代碼片斷找到第一個表,因爲它是Body的一個子表。如果它位於段落或其他內部,而不是直接的孩子,則可以使用後代

,就像我在我的示例中那樣。 –

相關問題