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

相关推荐
2501_907136824 小时前
HandyWrite Pro - word/excel转手写工具
word·软件需求
Eiceblue4 小时前
C# 如何实现 Word 转 Excel ?分享两种实用方法
c#·word·excel
天才少女爱迪生4 小时前
word格式规范检测+自动修改【python】
python·c#·word
gc_22995 小时前
学习C#调用OpenXml操作word文档的基本用法(29:学习中断类)
word·中断·openxml·break
梅孔立6 小时前
Aspose.Words Java 表格动态删列、合并列、表头重建、全局字体统一解决方案
java·开发语言·word·aspose·在线编辑
爱叨叨的小嘟1 天前
Latex公式 转 word可编辑公式
word·typora·latex
gc_22991 天前
学习C#调用OpenXml操作word文档的基本用法(27:学习文本运行类-续)
word·openxml·run·runproperties
ONLYOFFICE1 天前
如何将 Word 集成到 Web 应用程序? 5 种方法详解与对比
前端·word·onlyoffice
wolfengi1 天前
python之使用docxtpl渲染word模板
数据库·python·word