使用OpenXML导出到word文件,我搜索文本并将其替换为另一个文本。 工作代码是这样的:
Dim body = wdDoc.MainDocumentPart.Document.Body
Dim paras = body.Elements(Of DocumentFormat.OpenXml.Wordprocessing.Paragraph)()
Dim txtOfDoc = body.Elements(Of DocumentFormat.OpenXml.Wordprocessing.Text)()
For Each para In paras
For Each run In para.Elements(Of DocumentFormat.OpenXml.Wordprocessing.Run)()
For Each test In run.Elements(Of DocumentFormat.OpenXml.Wordprocessing.Text)()
If (test.Text.Contains(stringToReplace)) Then
test.Text = test.Text.Replace(stringToReplace, "newString")
Exit For
End If
Next
Next
Next
现在我想设置不同字体大小的字符串“newString”...
答案 0 :(得分:0)
我的解决方案是:
Dim body = wdDoc.MainDocumentPart.Document.Body
Dim paras = body.Elements(Of DocumentFormat.OpenXml.Wordprocessing.Paragraph)()
Dim txtOfDoc = body.Elements(Of DocumentFormat.OpenXml.Wordprocessing.Text)()
For Each para In paras
For Each run In para.Elements(Of DocumentFormat.OpenXml.Wordprocessing.Run)()
For Each test In run.Elements(Of DocumentFormat.OpenXml.Wordprocessing.Text)()
If (test.Text.Contains(stringToReplace)) Then
Dim tbl As New DocumentFormat.OpenXml.Wordprocessing.Table()
Dim tr As New DocumentFormat.OpenXml.Wordprocessing.TableRow()
Dim tc As New DocumentFormat.OpenXml.Wordprocessing.TableCell()
tc.Append(getFontDraft("DRAFT"))
tc.Append(New DocumentFormat.OpenXml.Wordprocessing.StyleTableCellProperties(New DocumentFormat.OpenXml.Wordprocessing.TableCellVerticalAlignment() With {.Val = DocumentFormat.OpenXml.Wordprocessing.TableVerticalAlignmentValues.Center}))
tr.Append(tc)
tbl.Append(tr)
para.AppendChild(tbl)
Exit For
End If
Next
Next
Next
Private Function getFontDraft(ByVal textIn As String) As DocumentFormat.OpenXml.Wordprocessing.Paragraph
Dim body As New DocumentFormat.OpenXml.Wordprocessing.Body()
Dim paragraph As New DocumentFormat.OpenXml.Wordprocessing.Paragraph()
Dim run_paragraph As New DocumentFormat.OpenXml.Wordprocessing.Run()
Dim text_paragraph As New DocumentFormat.OpenXml.Wordprocessing.Text(TextIn)
Dim RunProperties As DocumentFormat.OpenXml.Wordprocessing.RunProperties = run_paragraph.AppendChild(New DocumentFormat.OpenXml.Wordprocessing.RunProperties())
Dim Bold As New DocumentFormat.OpenXml.Wordprocessing.Bold
Bold.Val = OnOffValue.FromBoolean(True)
Dim fontSize As New DocumentFormat.OpenXml.Wordprocessing.FontSize
fontSize.Val = "32"
RunProperties.AppendChild(fontSize)
RunProperties.AppendChild(Bold)
run_paragraph.AppendChild(text_paragraph)
paragraph.Append(run_paragraph)
getFontDraft = paragraph
End Function