2013-09-25 5 views
2

Я использую Open XML, и я должен изменить текст в заголовке файла слова. Для изменения конкретного абзаца в документе я использовал следующий код:OpenXml Редактировать текст в заголовке файла слова

Dim body = wdDoc.MainDocumentPart.Document.Body 
      Dim paras = body.Elements(Of DocumentFormat.OpenXml.Wordprocessing.Paragraph)() 
      Dim header = body.Elements(Of DocumentFormat.OpenXml.Wordprocessing.Header)() 


      For Each para In paras 
       For Each run In para.Elements(Of DocumentFormat.OpenXml.Wordprocessing.Run)() 
        For Each testo In run.Elements(Of DocumentFormat.OpenXml.Wordprocessing.Text)() 
         If (testo.Text.Contains("<$doc_description$>")) Then 
          testo.Text = testo.Text.Replace("<$doc_description$>", "replaced-text") 
         End If 
        Next 
       Next 
      Next 

Заранее благодарим заранее!

ответ

6

Вы можете использовать следующий код, чтобы заменить тег в заголовке текстового документа:

Using wdDoc = WordprocessingDocument.Open("header.docx", True) 

    For Each headerPart In wdDoc.MainDocumentPart.HeaderParts 
    For Each currentParagraph In headerPart.RootElement.Descendants(Of DocumentFormat.OpenXml.Wordprocessing.Paragraph)() 
     For Each currentRun In currentParagraph.Descendants(Of DocumentFormat.OpenXml.Wordprocessing.Run)() 
     For Each currentText In currentRun.Descendants(Of DocumentFormat.OpenXml.Wordprocessing.Text)() 

      If (currentText.Text.Contains("$doc-description$")) Then 
      Console.WriteLine("found") 
      currentText.Text = currentText.Text.Replace("$doc-description$", "replaced-text") 
      End If 

     Next 
     Next 
    Next 
    Next 

End Using 

Во-первых, перечислить все HeaderParts в документе слова. Затем выполните поиск всех Text элементов , содержащих тег для замены. Затем замените тег на свой текст.

Обратите внимание, что вы должны использовать тег без <> и _ символов. Если тэг содержит эти символы, тогда слово разбивает текст на несколько элементов Text.

Если вы хотите изменить текст в таблице (или в любом другом элементе) просто поиск для всех Text элементов:

Using wdDoc = WordprocessingDocument.Open("header.docx", True) 

    For Each headerPart In wdDoc.MainDocumentPart.HeaderParts 
    For Each currentText In headerPart.RootElement.Descendants(Of DocumentFormat.OpenXml.Wordprocessing.Text)() 

     If (currentText.Text.Contains("$doc-description$")) Then 
     Console.WriteLine("found") 
     currentText.Text = currentText.Text.Replace("$doc-description$", "replaced-text") 
     End If 

    Next 
    Next 

End Using 
+0

@ andrea85: Я обновил свой ответ, чтобы показать, как заменить текст, содержащийся в таблице. Пожалуйста, примите/отпустите мой ответ, если это поможет вам, нажав на полую стрелку слева от ответа. – Hans

0

спасибо за ответ на самом деле работает :) Я также попытался с следующий код:

 
    For Each headref In mainDoc.Descendants(Of DocumentFormat.OpenXml.Wordprocessing.HeaderReference)() 
    headerRelationshipId = headref.Id.Value 
    headerType = headref.Type.Value.ToString() 
    Dim header01 As DocumentFormat.OpenXml.Wordprocessing.Header = DirectCast(wdDoc.MainDocumentPart.GetPartById(headerRelationshipId), HeaderPart).Header 
    Dim headerText As New StringBuilder() 

    For Each text00 As DocumentFormat.OpenXml.Wordprocessing.Text In header01.Descendants(Of DocumentFormat.OpenXml.Wordprocessing.Text)() 
     If (text00.Text.Contains("")) Then 
      text00.Text = text00.Text.Replace("", "replaced-text") 
     End If 
    Next 
Next 

Но если бы я хотел изменить текст в таблице (вместо абзаца)?

1

Портировано до C# от Ганса!

//Gets all the headers 
foreach (var headerPart in doc.MainDocumentPart.HeaderParts) 
{ 
     //Gets the text in headers 
     foreach(var currentText in headerPart.RootElement.Descendants<DocumentFormat.OpenXml.Wordprocessing.Text>()) 
     { 
      currentText.Text = currentText.Text.Replace("[Thanks]", "Thanks"); 
     } 
} 
Смежные вопросы