OpenXML如何使文本加粗

OpenXML how to make text bold

我使用 openXML 编写了一个包含我的文本的 word 文档。现在我想把部分文字加粗。然而,我无法找到使我的文字变粗的解决方案,因为我无法弄清楚。我的代码是:

        Dim FilePath As String = "C:\MyFolder\MyFile.docx"

        'Create a document to work in
        Using wordDocument As WordprocessingDocument = WordprocessingDocument.Create(FilePath, WordprocessingDocumentType.Document)
        ' Add a main document part.
        Dim mainPart As MainDocumentPart = wordDocument.AddMainDocumentPart()

        ' Create the document structure and add some text.
        mainPart.Document = New Document()
        Dim body As Body = mainPart.Document.AppendChild(New Body())
        Dim para As Paragraph = body.AppendChild(New Paragraph())
        Dim runNormal As Run = para.AppendChild(New Run())
        Dim runBold As Run = para.AppendChild(New Run())
        runBold.RunProperties.Bold()

我想要两个实例:一个用于普通文本 runNormal,一个用于粗体文本 runBold。遗憾的是,runBold 不起作用,而 runNormal 起作用。

参考以下代码

WordprocessingDocument doc = WordprocessingDocument.Create(path, WordprocessingDocumentType.Document)

Dim mainDocumentPart As MainDocumentPart = doc.AddMainDocumentPart()

mainDocumentPart.Document = New Document()

Dim body As Body = mainDocumentPart.Document.AppendChild(New Body())

Dim para As Paragraph = body.AppendChild(New Paragraph())

Dim run As Run = para.AppendChild(New Run())

Dim runProperties As RunProperties = run.AppendChild(New RunProperties())

Dim bold As Bold = New Bold()

bold.Val = OnOffValue.FromBoolean(True)

runProperties.AppendChild(bold)

run.AppendChild(New Text("Welcome!!!!!"))

doc.MainDocumentPart.Document.Save()

好的,我明白了它是如何工作的,所以这里是适合所有人的解决方案:

如果您是第一次在文本中用粗体书写,您需要使用:

Dim runProperties As RunProperties = run.AppendChild(New RunProperties(New Bold()))
run.AppendChild(New Text("I am written in bold!"))

现在,如果你想再次用粗体书写,请添加此代码:

run.AppendChild(New RunProperties(New Bold()))
run.AppendChild(New Text("I am also written in bold!"))

就是这样。总结一下,这里是完整的代码:

Using wordDocument As WordprocessingDocument = WordprocessingDocument.Create(DOCXPath, WordprocessingDocumentType.Document)
' Add a main document part.
Dim mainPart As MainDocumentPart = wordDocument.AddMainDocumentPart()

' Create the document structure
mainPart.Document = New Document()
Dim body As Body = mainPart.Document.AppendChild(New Body())
Dim para As Paragraph = body.AppendChild(New Paragraph())
Dim run As Run = para.AppendChild(New Run())
' Write in bold (only works in the first line which you write)
Dim runProperties As RunProperties = run.AppendChild(New RunProperties(New Bold()))
run.AppendChild(New Text("I am written in bold!"))
' If you want to write a second time in bold, just add the next line and afterwards your text to be written in bold.
run.AppendChild(New RunProperties(New Bold()))
run.AppendChild(New Text("I am also written in bold!"))