这个简短的教程指导如何在 C# 中使用密码保护 Excel 文件,并借助配置 IDE 的所有必要步骤和编写应用程序的详细步骤。它还提供了一个可运行的示例代码,展示了在 C# 中使用密码加密 Excel 文件的过程。您还将了解不同的加密类型、设置密码以及以不同格式保存输出文件,例如 XLSX、XLS、ODS 等。
在 C# 中密码保护 Excel 的步骤
- 建立使用 Aspose.Cells for .NET 加密 Excel 文件的环境
- 使用 Workbook 类对象加载或创建 Excel 文件
- 使用 SetEncryptionOptions() 方法为加载的工作簿设置所需的加密选项
- 设置文件密码
- 将加密的工作簿保存在磁盘上
这些步骤描述了密码保护 C# 中的 Excel 文件的过程,以便首先加载源 Excel 文件,然后使用 SetEncryptionOptions() 方法为电子表格设置不同的加密属性。在这些步骤之后,我们只需要设置打开 Excel 文件所需的密码,然后将输出的 Excel 文件保存为您想要的格式。
在 C# 中使用密码加密工作簿的代码
using System; | |
using Aspose.Cells; | |
namespace KBAspose | |
{ | |
class Program | |
{ | |
static void Main(string[] args) // Main function to encrypt Excel file | |
{ | |
// Initialize license | |
Aspose.Words.License licWords = new Aspose.Words.License(); | |
licWords.SetLicense("Aspose.Total.lic"); | |
// Load the Excel file | |
Workbook workbook = new Workbook("ExcelChart.xlsx"); | |
// Set Strong Encryption type | |
workbook.SetEncryptionOptions(EncryptionType.StrongCryptographicProvider, 128); | |
// Set Password | |
workbook.Settings.Password = "0987"; | |
// Save the excel file | |
workbook.Save("EncryptedWorkbook.xlsx"); | |
Console.WriteLine("Done"); | |
} | |
} | |
} |
此代码演示了使用 SetEncryptionOptions() 方法在 C#* 中加密 Excel 文件的过程,该方法采用加密类型值之一,如 StrongCryptographicProvider、EnhancedCryptographicProviderV1、Compatible 或 XOR 和密钥长度。 Workbook 类中的 Settings 对象具有密码属性,该属性设置为加密后打开 Workbook 所必需的。工作簿加密后,可以以任何 MS Excel 支持的格式保存。
在本文中,我们学习了加密 Excel 文件。如果您想了解将数字签名添加到工作簿的过程,请参阅 如何使用 C# 在 Excel 中添加数字签名 上的文章。