学习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);
}

参考文献

1\]https://github.com/dotnet/Open-XML-SDK \[2\]https://learn.microsoft.com/zh-cn/office/open-xml/open-xml-sdk \[3\]https://learn.microsoft.com/zh-cn/dotnet/api/documentformat.openxml.wordprocessing.style?view=openxml-3.0.1 \[4\]https://blog.csdn.net/i042416/article/details/126228816 \[5\]https://www.php.cn/faq/2234830.html \[6\]https://wiki.services.openoffice.org/w/index.php?title=OOXML/WordProcessingML\&direction=prev\&oldid=235815

相关推荐
微软Nav/BC专家1 天前
Microsoft Dynamics 365 Business Central Word Add-in如何安装
word·微软erp
大C聊AI1 天前
标书高效制作:Word 排版快捷键 + AI 工具组合工作流
word·办公技巧·效率提升·招投标·智标领航
jianwuhuang821 天前
豆包输出word
人工智能·ai·chatgpt·word·deepseek·ai导出鸭
chatexcel3 天前
ChatExcel AI文档上线:AI自动生成Word报告的完整工作流
人工智能·word
俊哥工具3 天前
不用安装不收费!多功能U盘修复工具,解决大部分U盘故障
学习·pdf·word·excel·音视频
草丛中的蝈蝈3 天前
word目录中的一级标题编号和标题之间距离很大,但是内容里是正常的
word
Metaphor6924 天前
使用 Python 设置 Word 文档文本的颜色
python·word
usdoc文档预览4 天前
国产化踩坑:Vue3 / React / 小程序如何免插件实现 OFD 及复杂 Office 文档同屏预览
前端·javascript·react.js·小程序·pdf·word·office文件在线预览
一头爱吃肉的牛4 天前
Word转PPT教程:三步用AI工具一键生成
人工智能·word·powerpoint
熟悉的新风景5 天前
word,wps使用技巧
word·wps