关于c#:CVBNET-如何在Word中插入日期选择控件

5次阅读

共计 1879 个字符,预计需要花费 5 分钟才能阅读完成。

微软 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。

正文完
 0