下拉列表是内容控件的一种,是咱们比拟罕用的一个性能。它可能限定编辑的内容,只能抉择列表里的数据录入,不便填写的同时,保障了录入数据的准确性。在微软Word中,增加控件的性能默认是敞开的,须要关上开发工具能力增加控件。但在Word文档中增加内容控件并非只能通过微软Word实现,还可通过编程实现。通过代码增加内容控件无需微软Word,同时可能集成到本人的我的项目、程序中,对于开发者来说十分不便。本文将介绍用代码实现在Word文档中增加下拉列表控件的操作方法。
本文所用到的办法须要一个收费的Word库的,Free Spire.Doc for .NET,需先引入DLL文件才可在代码中援用。
1. 通过Nuget引入
1.1 在Nuget治理界面中搜寻FreSpire.Doc装置。
1.2 在控制台输出以下代码装置。
PM> Install-Package FreeSpire.Doc
小标题
2. 手动下载增加DLL
拜访Free Spire.Doc for .NET官网,下载并解压文件,而后在我的项目依赖项中增加DLL文件。
在Word文档中增加下拉列表
增加下拉列表的具体操作步骤如下:
- 创立 Document 类的对象。
- 用 Document.LoadFromFile() 办法从磁盘载入Word文档。
- 在文档中增加一个段落。
- 创立内容控件。
- 用 Paragraph.ChildObjects.Add() 办法将内容控件插入到创立的段落中。
- 用 StructuredDocumentTagInline.SDTProperties.SDTType 属性将内容控件设置为下拉列表控件(DropDownList)。
- 用 StructuredDocumentTagInline.SDTProperties.ControlProperties 属性增加下拉列表选项。
- 用 StructuredDocumentTagInline.SDTContent.ChildObjects.Add() 办法设置下拉列表显示的选项。
- 用 Document.SaveToFIle() 办法保存文档。
代码示例:
using System;
using System.Drawing;
using Spire.Doc;
using Spire.Doc.Fields;
using Spire.Doc.Documents;
namespace AddContentControl
{
internal class Program
{
static void Main(string[] args)
{
//创立Word文档
Document document = new Document();
//从磁盘加载Word文档
document.LoadFromFile(@"C:\Users\Allen\Desktop\Sample3.docx");
//在文档中增加一个段落
Section section = document.Sections[0];
Paragraph paragraph = section.AddParagraph();
TextRange text = paragraph.AppendText("下拉列表控件: ");
text.CharacterFormat.FontSize = 14;
text.CharacterFormat.FontName = "微软雅黑";
//创立内容控件
StructureDocumentTagInline sd = new StructureDocumentTagInline(document);
//将内容控件插入到创立的段落
paragraph.ChildObjects.Add(sd);
//将内容控件的类型设置为下拉列表控件
sd.SDTProperties.SDTType = SdtType.DropDownList;
//增加下拉列表选项
SdtDropDownList sddl = new SdtDropDownList();
sddl.ListItems.Add(new SdtListItem("选项1"));
sddl.ListItems.Add(new SdtListItem("选项2"));
sddl.ListItems.Add(new SdtListItem("选项3"));
sd.SDTProperties.ControlProperties = sddl;
//设置下拉列表显示的选项
TextRange rt = new TextRange(document);
rt.Text = sddl.ListItems[0].DisplayText;
sd.SDTContent.ChildObjects.Add(rt);
//保存文档
document.SaveToFile("Output.docx", FileFormat.Docx);
}
}
}
增加成果示意:
以上所应用的代码援用项均来自收费的Free Spire.Doc for .NET。
发表回复