文本格式
段落中的文本可以有多种格式,例如:
RtfString表示带格式的文本,要生成上面的Word文档, 可以按顺序增加多个RtfString并设置格式,参考代码 如下:
Dim
wdc
As
New
WordCreator()
Dim
prg
As
New
Word.Objects.RtfParagraph()
'定义段落
wdc.Add(prg)
'将段落添加到文档中
Dim
fnt
As
New
Font("宋体",
12)
Dim
str
As
New
Word.Objects.RtfString("Foxtable",
fnt, Word.RtfUnderlineStyle.Single)
'定义第一个文本,有下划线
prg.Add(str)
'将第一个文本添加到段落中
str =
New
Word.Objects.RtfString("
2024 ",
fnt)
'定义第二个文本
str.BackColor = Color.Red
'红底
str.ForeColor = Color.White
'白字
prg.Add(str)
'将第二个文本添加到段落中
prg.Add(New
Word.Objects.RtfString("即将发布,有四个重大更新!",
fnt))
'直接添加第三个文本到段落中
prg.Add(New
word.Objects.RtfLineBreak())
'另起一行
prg.Add(New
word.Objects.RtfLineBreak())
'再另起一行,等于增加一个空行
prg.Add(New
Word.Objects.RtfString("A",
fnt))
'直接添加第四个文本到段落中
str =
New
Word.Objects.RtfString("2",
fnt)
'定义第五个文本
str.Superscript =
True
'第五个文本为上标
prg.Add(str)
'将第五个文本添加到段落中
prg.Add(New
Word.Objects.RtfString("
+ B",
fnt))
'直接添加第六个文本到段落中
str =
New
Word.Objects.RtfString("2",
fnt)
'定义第七个文本
str.Superscript =
True
'第七个文本文上标
prg.Add(str)
'将第七个文本添加到段落中
prg.Add(New
Word.Objects.RtfString("
= C",
fnt))
'直接添加第八个文本到段落中
str =
New
Word.Objects.RtfString("2",
fnt)
'定义第九个文本
str.Superscript =
True
'第九个文本为上标
prg.Add(str)
'将第九个文本添加到段落中
Dim
fl
As
String
=
"c:\temp\test.docx"
wdc.Save(fl)
Process.Start(fl)
代码比较长,但并不复杂,只是先后定义了九个有不同格式的RtfString对象,顺序添加到段落(RtfParagraph)中。
RtfString
RtfString表示带格式的文本,其主要属性有:
属性 | 说明 |
Font | 文本字体 |
BackColor | 背景颜色 |
ForeColor | 文本颜色 |
Superscript | 是否上标 |
Subscript | 是否下标 |
Expand | 字符间距 |
Underline | 下划线样式 |
Text | 文本内容 |
定义RtfString的语法为:
Dim 变量名 As New RtfString(text, font, underline)
参数 | 说明 |
text | 字符型,指定文本内容 |
font | 可选参数,用于指定文本字体 |
underline | 可选参数,逻辑型,是否有下划线 |
RtfString可以不通过RtfParagraph,直接添加到文档中,RtfString不会换行,会直接附加在前一个RtfString之后,例如:
Dim
wdc
As
New
WordCreator()
Dim
fnt
As
New
Font("宋体",
12)
wdc.Add(
New
Word.Objects.RtfString(
"Foxtable是电子表格,",
fnt))
wdc.Add(
New
Word.Objects.RtfString(
"Foxtable也是数据库。",
fnt))
Dim
rtr
As
New
Word.Objects.RtfString(
"Foxtable是一个优秀的应用软件,",
fnt)
rtr.ForeColor = Color.Brown
wdc.Add(rtr)
rtr =
New
Word.Objects.RtfString(
"Foxtable也是一个高效率的开发工具!",
fnt)
rtr.ForeColor = Color.Green
wdc.Add(rtr)
Dim
fl
As
String
=
"c:\temp\test.docx"
wdc.Save(fl)
'保存文件
Process.Start(fl)
'打开文件
生成的文档为: