- A+
所属分类:.NET技术
一、程序环境
以下内容通过C#及VB.NET代码demo示例介绍如何给Excel文档添加数字签名,以及删除Excel文档中已有的数字签名。工具使用最近发布的Spire.XLS for .NET 版本10.11.2,可在官网下载包,或者通过Nuget搜索下载;编辑代码前,注意先将Spire.XLS.dll添加引用到VS,并添加相应using指令,如下添加引用效果:
二、Java Demo示例代码
1. 添加数字签名
C#
using Spire.Xls; using Spire.Xls.Core.MergeSpreadsheet.Interfaces; using System; using System.Security.Cryptography.X509Certificates; namespace DigitalSignature_XLS { class Program { static void Main(string[] args) { //创建Workbook实例 Workbook workbook = new Workbook(); //加载Excel文档 workbook.LoadFromFile("sample.xlsx"); //添加数字签名 X509Certificate2 cert = new X509Certificate2("gary.pfx", "123456"); DateTime certtime = new DateTime(2020, 7, 1, 7, 10, 36); IDigitalSignatures signature = workbook.AddDigitalSignature(cert, "Manager", certtime); //保存文档 workbook.SaveToFile("AddDigitalSignature.xlsx", FileFormat.Version2013); System.Diagnostics.Process.Start("AddDigitalSignature.xlsx"); } } }
VB.NET
Imports Spire.Xls Imports Spire.Xls.Core.MergeSpreadsheet.Interfaces Imports System.Security.Cryptography.X509Certificates Namespace DigitalSignature_XLS Class Program Private Shared Sub Main(args As String()) '创建Workbook实例 Dim workbook As New Workbook() '加载Excel文档 workbook.LoadFromFile("sample.xlsx") '添加数字签名 Dim cert As New X509Certificate2("gary.pfx", "123456") Dim certtime As New DateTime(2020, 7, 1, 7, 10, 36) Dim signature As IDigitalSignatures = workbook.AddDigitalSignature(cert, "Manager", certtime) '保存文档 workbook.SaveToFile("AddDigitalSignature.xlsx", FileFormat.Version2013) System.Diagnostics.Process.Start("AddDigitalSignature.xlsx") End Sub End Class End Namespace
数字签名添加效果:
2. 删除Excel中的数字签名
C#
using Spire.Xls; namespace RemoveSignature { class Program { static void Main(string[] args) { //加载Excel文档 Workbook workbook = new Workbook(); workbook.LoadFromFile("AddDigitalSignature.xlsx"); //删除文档中的数字签名 workbook.RemoveAllDigitalSignatures(); //保存文档 workbook.SaveToFile("RemoveDigitalSignature.xlsx", FileFormat.Version2013); System.Diagnostics.Process.Start("RemoveDigitalSignature.xlsx"); } } }
VB.NET
Imports Spire.Xls Namespace RemoveSignature Class Program Private Shared Sub Main(args As String()) '加载Excel文档 Dim workbook As New Workbook() workbook.LoadFromFile("AddDigitalSignature.xlsx") '删除文档中的数字签名 workbook.RemoveAllDigitalSignatures() '保存文档 workbook.SaveToFile("RemoveDigitalSignature.xlsx", FileFormat.Version2013) System.Diagnostics.Process.Start("RemoveDigitalSignature.xlsx") End Sub End Class End Namespace
运行程序后,原有的签名已删除。