微软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文档中增加日期抉择控件
增加日期抉择控件的具体操作步骤如下:
- 创立Word文档。
- 用 Document.LoadFromFile() 办法从磁盘载入Word文档。
- 在文档中增加一个段落。
- 创立内容控件。
- 用 Paragraph.ChildObjects.Add() 办法将内容控件插入到创立的段落中。
- 用 StructuredDocumentTagInline.SDTProperties.SDTType 属性将内容控件设置为日期抉择控件(DatePicker)。
- 用 SdtDate.CalendarType 属性设置日历类型。
- 用 SdtDate.DateFormat 属性设置日期格局。
- 用 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.DatePicker; //设置日历类型 SdtDate date = new SdtDate(); date.CalendarType = CalendarType.Default; //设置日期格局 date.DateFormat = "yyyy.MM.dd"; //设置控件内容为日期 date.FullDate = DateTime.Now; sd.SDTProperties.ControlProperties = date; //设置控件显示日期 TextRange rt = new TextRange(document); rt.Text = "2022.06.30"; sd.SDTContent.ChildObjects.Add(rt); //保存文档 document.SaveToFile("Output.docx", FileFormat.Docx); } }}
增加成果示意:
以上援用的代码均来自收费的Free Spire.Doc for .NET。