学习C#调用OpenXml操作word文档的基本用法(28:学习文本类)

  文本类Text是openxml中用于保存纯文本内容的核心类,命名空间为DocumentFormat. OpenXml.Wordprocessing,对应document.xml文件内的<w:t>元素,负责保存word文档里真正可读、可编辑的文字信息。

  在openxml的wrod文档结构里,文本不能直接放在段落(Paragraph)下,必须按照段落类(Paragraph)、文本运行类(Run)、文本类(Text)的层级关系创建对象,Text对象保存文本内容,文本格式放在文本运行类中,而段落格式在放在段落类中,最简单的wrod文档的xml结构如下所示(参考文献6)。

  文本类Text的类继承链为OpenXmlElement -> OpenXmlLeafElement -> OpenXmlLeafTextElement -> TextType -> Text,其主要属性包括以下两个:
  1)Text属性:保存纯文本字符串内容;
  2)Space属性:设置文本中空白字符的处理方式(应该主要针对文本两头的空白字符),从枚举值SpaceProcessingModeValues内取值,值为Default会合并连续空格,值为Preserve则可保留。
  下面示例程序用于将输入的文本保存为word文档,由运行结果截图可知,文本内部的空格保留不变,但开头的空格默认去掉了。

csharp 复制代码
using (WordprocessingDocument wordDocument = WordprocessingDocument.Create(sfd.FileName, WordprocessingDocumentType.Document))
{
    MainDocumentPart mainPart = wordDocument.AddMainDocumentPart();
    mainPart.Document = new Document();
    Body body = mainPart.Document.AppendChild(new Body());
    
    Paragraph paragraph = body.AppendChild(new Paragraph());
    Run run = paragraph.AppendChild(new Run());

    Text text = new Text();
    text.Text = txtContent.Text;
    run.AppendChild(text);
}

  将Space属性设置为Preserve,再次运行程序,则在word文档中会保留开头处的空格。

csharp 复制代码
using (WordprocessingDocument wordDocument = WordprocessingDocument.Create(sfd.FileName, WordprocessingDocumentType.Document))
{
    MainDocumentPart mainPart = wordDocument.AddMainDocumentPart();
    mainPart.Document = new Document();
    Body body = mainPart.Document.AppendChild(new Body());
    
    Paragraph paragraph = body.AppendChild(new Paragraph());
    Run run = paragraph.AppendChild(new Run());

    Text text = new Text();
    text.Space = SpaceProcessingModeValues.Preserve;
    text.Text = txtContent.Text;
    run.AppendChild(text);
}

参考文献

1https://github.com/dotnet/Open-XML-SDK

2https://learn.microsoft.com/zh-cn/office/open-xml/open-xml-sdk

3https://learn.microsoft.com/zh-cn/dotnet/api/documentformat.openxml.wordprocessing.style?view=openxml-3.0.1

4https://blog.csdn.net/i042416/article/details/126228816

5https://www.php.cn/faq/2234830.html

6https://wiki.services.openoffice.org/w/index.php?title=OOXML/WordProcessingML\&direction=prev\&oldid=235815

相关推荐
Matt Feng18 小时前
PDF加水印和密码:6项权限设置与完整步骤
pdf·word·wps
Am-Chestnuts1 天前
markdown复制到word格式乱了怎么办?
word·markdown·pandoc·wps·格式
Tjohn91 天前
新电脑word打字一卡一卡的,删除也一卡一卡的?(含解决办法)
word
百事牛科技1 天前
Word加密技巧:打开密码和修改密码的正确用法
windows·word
Metaphor6922 天前
使用 Python 轻松调整 Word 文档的页边距
python·word·页边距
Jazz_z2 天前
C# 实现 Word 文档内容复制
开发语言·c#·word
姜乂元3 天前
使用 Delphi 开发 Word COM Add-ins 插件
word·delphi·com·add-ins
Matt Feng3 天前
在线PDF加密码水印怎么用?水印与权限设置步骤
运维·服务器·pdf·word·wps
开开心心就好3 天前
电脑小毛病修复工具,不用重装系统了
智能手机·pdf·电脑·word·音视频·laravel·perl
开开心心就好9 天前
电脑禁止自动休眠工具,还能按负载定时
算法·智能手机·pdf·电脑·word·音视频·lua