学习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

相关推荐
Sour6 小时前
Word 文档翻译后保留格式的检查清单:标题、表格、图片、目录和批注
pdf·word·办公软件·office·文档翻译
qq_422152571 天前
Word 文件太大怎么压缩?2026 年文档瘦身方案对比
开发语言·c#·word
子非衣1 天前
Java使用Aspose进行Word转PDF时异常卡主问题
java·pdf·word
E_ICEBLUE1 天前
将 Excel 表格插入 Word 文档的三种实用方案(Python 自动化)
python·word·excel
俊哥工具1 天前
027免费开源硬盘检测工具,一键查看健康度,杜绝数据丢失
pdf·电脑·word·excel·音视频
DS随心转插件2 天前
AI 导出鸭实测:Markdown TO Word 本地化转换能力深度评测,多角度拆解本地化转换真实表现
人工智能·ai·word·wps·deepseek·ai导出鸭
DS随心转插件2 天前
AI 导出鸭实操教程:Markdown 转 Word 高效协作与隐私交付实战指南
人工智能·ai·word·豆包·deepseek·ai导出鸭
AI导出鸭PC端2 天前
ChatGPT怎么生成word文档?「AI 导出鸭」解决格式丢失痛点
人工智能·ai·chatgpt·word·豆包·ai导出鸭
SunnyDays10112 天前
Java 操作 Word 超链接:添加网页、邮箱、文件和图片链接
java·word·超链接
SunnyDays10112 天前
Python 操作 Word 文档目录详解:创建、更新、提取与删除
python·word·目录