inv*_*306 4 vb.net asp.net openxml
我正在使用Open XML,我应该更改word文件标题中的文本.要更改文档中的特定段落,我使用了以下代码:
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
Run Code Online (Sandbox Code Playgroud)
提前致谢!
从 Hans 的答案移植到 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");
}
}
Run Code Online (Sandbox Code Playgroud)
您可以使用以下代码替换word文档标题中的标记:
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
Run Code Online (Sandbox Code Playgroud)
首先,枚举所有HeaderPartsword文档.然后搜索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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6661 次 |
| 最近记录: |