2013-10-15 50 views
0

我有一個10頁的文檔。每個頁面都有一個頁眉和頁腳。標題可能有兩行文字或一行,每一行都有不同的風格。想要做的是循環遍歷文檔。閱讀每個頁面的頁眉和頁腳,將其放入DataTable,以便稍後構建TOC。任何想法,我嘗試過,但它不能正常工作,它不讀取每頁頁腳和跳過頁面(這似乎沒有順序,我想按頁順序獲取值,因爲它似乎跳過第一頁,直到最後一頁迭代)。OpenXML asp.net通過標題循環

幫助,將不勝感激。 JT

Using wordDoc As WordprocessingDocument = WordprocessingDocument.Open(combineDocName, True) 
     For Each Head As HeaderPart In wordDoc.MainDocumentPart.HeaderParts 
      For Each currentParagraph As DocumentFormat.OpenXml.Wordprocessing.Paragraph In Head.RootElement.Descendants(Of DocumentFormat.OpenXml.Wordprocessing.Paragraph)() 
      Dim p As ParagraphProperties = currentParagraph.Elements(Of ParagraphProperties)().First() 
       If p.Count > 0 Then 
        If (p.ParagraphStyleId IsNot Nothing) Then 
         If p.ParagraphStyleId.Val.ToString() = "HeaderBar" Then 
          For Each currentText As Text In Head.RootElement.Descendants(Of DocumentFormat.OpenXml.Wordprocessing.Text)() 
           If (String.IsNullOrEmpty(keepHeaderM)) Then 
            HeaderBarTxt = currentText.Text.Trim() 
           ElseIf keepHeaderM <> currentText.Text.Trim() Then 
            HeaderBarTxt = currentText.Text.Trim() 
           End If 
          Next 
         ElseIf p.ParagraphStyleId.Val.ToString() = "NavigationBar" Then 
          For Each currentText As Text In Head.RootElement.Descendants(Of DocumentFormat.OpenXml.Wordprocessing.Text)() 
           iCount = currentText.Text.Split(":").Length - 1 
           If (String.IsNullOrEmpty(keepHeaderM)) Then 
            HeaderTxt = currentText.Text.Trim() 
           ElseIf keepHeaderM <> currentText.Text.Trim() Then 
            HeaderTxt = currentText.Text.Trim() 
           End If 
          Next 
         End If 
        End If 
       End If 
      Next 
      Next 
      For Each foot As FooterPart In wordDoc.MainDocumentPart.FooterParts 
       For Each currentParagraph2 As DocumentFormat.OpenXml.Wordprocessing.Paragraph In foot.RootElement.Descendants(Of DocumentFormat.OpenXml.Wordprocessing.Paragraph)() 
        If currentParagraph2.Count > 0 Then 
         For Each currentText2 As Text In foot.RootElement.Descendants(Of DocumentFormat.OpenXml.Wordprocessing.Text)() 
          Dim strTemp As String = currentText2.Text 
          If strTemp.IndexOf("-") <> -1 Then 
           FooterTxt = currentText2.Text.Trim() 

          End If 
         Next 
        End If 

       Next 
      Next 
end using 
+0

恰好是不工作怎麼辦?文件的格式是什麼? – Patrik

+0

我發現當你循環它不會這樣做,因爲我需要的是如何循環瀏覽頁面......我嘗試了以下內容,但我仍然首先獲得第三頁,並且第一頁最後一頁原因。我如何依次循環播放? – user2883963

回答

0

如果您在Word文件中有不同的頁眉和頁腳,那麼我假設您的Word文檔中有多個部分。

你必須通過這些部分進行迭代,然後在閱讀部分的頁腳和頭文件,然後保存在某個地方他們的DataTable。

即將創造一個TOC的問題。

你可以做的是創建具有手動創建說TOC.docx一個TOC一個單獨的Word文檔。 現在,當您要添加TOC時,您將創建TOC.docx的副本,然後將此文件與您要TOC的文檔合併。 不要忘記在合併文檔的設置中將自動更新設置爲true。

<w:updateFields w:val="true" />