C#/VB.NET 給Excel新增、刪除數字簽名
阿新 • • 發佈:2020-11-11
一、程式環境
以下內容通過C#及VB.NET代介紹如何給Excel文件新增數字簽名,以及刪除Excel文件中已有的數字簽名。工具使用最近釋出的Spire.XLS for .NET 版本10.11.2,可在官網下載包,或者通過Nuget搜尋下載;編輯程式碼前,注意先將Spire.XLS.dll新增引用到VS,並新增相應using指令,如下新增引用效果:
二、C# / VB示例程式碼
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
執行程式後,原有的簽名已刪除。
&n