Word控件Spire.Doc 【文本】教程(7) ;C#获取Word文档中内容控件的别名、标签和ID

内容控件为您提供了一种设计文档的方法。当您向文档添加内容控件时,该控件由边框、标题和可以向用户提供说明的临时文本标识。根据微软的说法,内容控件主要受益于两个功能:

  • 将文档或模板的部分内容绑定到数据。您可以将内容控件绑定到数据库字段、.NET Framework 中的托管对象、存储在文档中的 XML 元素以及其他数据源。

首先,检查包含六个按行和表格分布的内容控件的测试文件。默认情况下,如果我们不点击受保护的部分,控件的边框和标题不会出现。

测试文件:

C#获取Word文档中内容控件的别名、标签和ID

主要步骤

第 1 步:创建一个新的 Word 文档并加载测试文件。

第 2 步:创建两个列表来存储标签,这些标签分别以行和表的形式分布。在这里,每个内容控件都将由标签标识。

第 3 步:使用foreach语句获取Word文档中的所有标签。

完整代码

static void Main(string[] args){using (Document document = new Document(@"....TestDatatest.docx")){StructureTags structureTags = GetAllTags(document);List<StructureDocumentTagInline> tagInlines = structureTags.tagInlines;string alias = tagInlines[0].SDTProperties.Alias;decimal id = tagInlines[0].SDTProperties.Id;string tag = tagInlines[0].SDTProperties.Tag;List<StructureDocumentTag> tags = structureTags.tags;alias = tags[0].SDTProperties.Alias;id = tags[0].SDTProperties.Id;tag = tags[0].SDTProperties.Tag;}}static StructureTags GetAllTags(Document document){StructureTags structureTags = new StructureTags();foreach (Section section in document.Sections){foreach (DocumentObject obj in section.Body.ChildObjects){if (obj.DocumentObjectType == DocumentObjectType.Paragraph){foreach (DocumentObject pobj in (obj as Paragraph).ChildObjects){if (pobj.DocumentObjectType == DocumentObjectType.StructureDocumentTagInline){structureTags.tagInlines.Add(pobj as StructureDocumentTagInline);}}}else if (obj.DocumentObjectType == DocumentObjectType.Table){foreach (TableRow row in (obj as Table).Rows){foreach (TableCell cell in row.Cells){foreach (DocumentObject cellChild in cell.ChildObjects){if (cellChild.DocumentObjectType == DocumentObjectType.StructureDocumentTag){structureTags.tags.Add(cellChild as StructureDocumentTag);}else if (cellChild.DocumentObjectType == DocumentObjectType.Paragraph){foreach (DocumentObject pobj in (cellChild as Paragraph).ChildObjects){if (pobj.DocumentObjectType == DocumentObjectType.StructureDocumentTagInline){structureTags.tagInlines.Add(pobj as StructureDocumentTagInline);}}}}}}}}}return structureTags;}public class StructureTags{List<StructureDocumentTagInline> m_tagInlines;public List tagInlines{get{if (m_tagInlines == null)m_tagInlines = new List();return m_tagInlines;}set{m_tagInlines = value;}}List<StructureDocumentTag> m_tags;public List tags{get{if (m_tags == null)m_tags = new List();return m_tags;}set{m_tags = value;}}}

效果截图

行中的内容控件

C#获取Word文档中内容控件的别名、标签和ID

表格中的内容控件

C#获取Word文档中内容控件的别名、标签和ID

欢迎下载|体验更多E-iceblue产品

获取更多信息请咨询在线客服  


标签:

声明:本站部分文章及图片源自用户投稿,如本站任何资料有侵权请您尽早请联系jinwei@zod.com.cn进行处理,非常感谢!

上一篇 2022年6月23日
下一篇 2022年6月24日

相关推荐

发表回复

登录后才能评论