如何在 C# 中为工作簿设置密码

如何在 C# 中为工作簿设置密码

This article was translated from English: Does it need improvement?
Translated
View the article in English

IronXL使开发人员能够通过一次方法调用在 C# 中对 Excel 工作簿进行密码保护——使用 Encrypt 方法并输入您想要的密码,然后保存工作簿即可立即应用保护。

快速入门:使用IronXL工作簿密码

IronXL 只需一个简单的步骤即可让开发人员加密 Excel 工作簿——无需互操作,轻松便捷。 使用 Encrypt 方法并输入您的密码,然后保存文件即可立即保护您的工作簿。

  1. 使用 NuGet 包管理器安装 https://www.nuget.org/packages/IronXL.Excel

    PM > Install-Package IronXL.Excel
  2. 复制并运行这段代码。

    var wb = WorkBook.Load("input.xlsx"); wb.Encrypt("MyStrongPass"); wb.SaveAs("input.xlsx");
  3. 部署到您的生产环境中进行测试

    通过免费试用立即在您的项目中开始使用IronXL

    arrow pointer


如何访问受密码保护的工作簿?

可以通过将密码作为第二个参数传递给 Load 方法来打开受保护的电子表格。 例如:WorkBook.Load("sample.xlsx", "IronSoftware")。 This feature is essential when working with existing Excel files that have been secured by colleagues or automated processes.

请注意没有正确的密码,无法打开受保护的电子表格

下面是一个完整的示例,演示如何访问受密码保护的工作簿:

using IronXL;

// Attempt to open a password-protected workbook
try 
{
    WorkBook protectedWorkBook = WorkBook.Load("encrypted_data.xlsx", "MySecretPass123!");

    // Access the first worksheet
    WorkSheet sheet = protectedWorkBook.WorkSheets[0];

    // Read data from protected file
    var cellValue = sheet["A1"].Value;
    Console.WriteLine($"Successfully accessed protected workbook. A1 contains: {cellValue}");
}
catch (Exception ex)
{
    Console.WriteLine($"Failed to open workbook: {ex.Message}");
}
using IronXL;

// Attempt to open a password-protected workbook
try 
{
    WorkBook protectedWorkBook = WorkBook.Load("encrypted_data.xlsx", "MySecretPass123!");

    // Access the first worksheet
    WorkSheet sheet = protectedWorkBook.WorkSheets[0];

    // Read data from protected file
    var cellValue = sheet["A1"].Value;
    Console.WriteLine($"Successfully accessed protected workbook. A1 contains: {cellValue}");
}
catch (Exception ex)
{
    Console.WriteLine($"Failed to open workbook: {ex.Message}");
}
$vbLabelText   $csharpLabel

如果我用错密码会怎样?

当提供的密码不正确时,IronXL 会抛出异常,而不是返回空值或空工作簿。 这种行为可以防止未经授权的访问尝试,从而确保安全性。始终用 try-catch 块封装受密码保护的工作簿操作,以便从容应对身份验证失败。 If you're building an application that processes multiple Excel files, consider implementing a retry mechanism with user prompts for password entry.

我能否在打开工作簿之前检查其是否受密码保护?

遗憾的是,Excel 的文件格式不允许在不尝试打开文件的情况下检查密码保护状态。建议的方法是先尝试在没有密码的情况下加载文件,然后捕捉异常并在需要时使用密码重试。 This pattern works well when managing multiple worksheets with mixed protection levels.

如何在工作簿中应用密码?

要为电子表格设置密码保护,请使用如下代码所示的 Encrypt 方法:

:path=/static-assets/excel/content-code-examples/how-to/set-password-workbook-protect.cs
WorkBook workBook = WorkBook.Load("sample.xlsx");

// Open protected spreadsheet file
WorkBook protectedWorkBook = WorkBook.Load("sample.xlsx", "IronSoftware");

// Set protection for spreadsheet file
workBook.Encrypt("IronSoftware");

workBook.Save();
$vbLabelText   $csharpLabel

For more advanced scenarios, you can combine workbook encryption with worksheet-level protection:

using IronXL;
using System;

// Create a new workbook with sensitive financial data
WorkBook workBook = WorkBook.Create(ExcelFileFormat.XLSX);
WorkSheet sheet = workBook.CreateWorkSheet("FinancialData");

// Add sensitive data
sheet["A1"].Value = "Confidential Financial Report";
sheet["A3"].Value = "Revenue";
sheet["B3"].Value = 1250000;
sheet["A4"].Value = "Expenses";
sheet["B4"].Value = 750000;

// Apply formatting before encryption
sheet["B3:B4"].FormatCells.FormatString = "$#,##0.00";

// Encrypt the workbook with a strong password
workBook.Encrypt("F!n@nc3_S3cur3_2024");

// Save the encrypted workbook
workBook.SaveAs("financial_report_encrypted.xlsx");

Console.WriteLine("Workbook encrypted successfully!");
using IronXL;
using System;

// Create a new workbook with sensitive financial data
WorkBook workBook = WorkBook.Create(ExcelFileFormat.XLSX);
WorkSheet sheet = workBook.CreateWorkSheet("FinancialData");

// Add sensitive data
sheet["A1"].Value = "Confidential Financial Report";
sheet["A3"].Value = "Revenue";
sheet["B3"].Value = 1250000;
sheet["A4"].Value = "Expenses";
sheet["B4"].Value = 750000;

// Apply formatting before encryption
sheet["B3:B4"].FormatCells.FormatString = "$#,##0.00";

// Encrypt the workbook with a strong password
workBook.Encrypt("F!n@nc3_S3cur3_2024");

// Save the encrypted workbook
workBook.SaveAs("financial_report_encrypted.xlsx");

Console.WriteLine("Workbook encrypted successfully!");
$vbLabelText   $csharpLabel

为什么密码只有在保存后才生效?

Excel 的加密过程会修改文件的内部结构,这需要写入磁盘。 直到您调用 Save()SaveAs() 时,工作簿才会保留在内存中,而不会应用加密。 这种设计允许您在提交加密版本之前进行多次修改。 When working with workbook metadata, remember to set all properties before applying encryption and saving.

我应该使用什么强度的密码?

对于商业应用,请遵循以下密码指南:

  • 至少 12 个字符的长度
  • 混合使用大写和小写字母
  • 包含数字和特殊字符
  • 避免使用字典词汇或可预测的模式
  • 可以考虑使用 "MyExcel@Report#2024!"这样的短语。

When developing applications that export sensitive data to Excel, implement a password policy that enforces these requirements programmatically.

我可以只对特定工作表进行密码保护吗?

是的! IronXL 支持工作簿级和工作表级保护。 工作簿加密可以防止未经授权的文件访问,而工作表保护则可以防止对特定工作表进行修改。 您可以将两种方法结合起来:

// Load workbook
WorkBook workBook = WorkBook.Load("multi_sheet_report.xlsx");

// Protect specific worksheets
workBook.WorkSheets["Summary"].ProtectSheet("SheetPass123");
workBook.WorkSheets["Details"].ProtectSheet("DetailPass456");

// Then encrypt the entire workbook
workBook.Encrypt("MasterPassword789!");

// Save with both protections
workBook.Save();
// Load workbook
WorkBook workBook = WorkBook.Load("multi_sheet_report.xlsx");

// Protect specific worksheets
workBook.WorkSheets["Summary"].ProtectSheet("SheetPass123");
workBook.WorkSheets["Details"].ProtectSheet("DetailPass456");

// Then encrypt the entire workbook
workBook.Encrypt("MasterPassword789!");

// Save with both protections
workBook.Save();
$vbLabelText   $csharpLabel
C# code showing WorkBook.Load() and WorkBook.Encrypt() methods with file explorer displaying Excel files

如何从工作簿中删除密码?

要从电子表格中删除密码,只需将 Password 字段设置为 null,如下面的代码所示:

请注意只有在访问工作簿后才能执行此操作。 因此,必须知道原始密码。

:path=/static-assets/excel/content-code-examples/how-to/set-password-workbook-unprotect.cs
// Remove protection for opened workbook. Original password is required.
workBook.Password = null;
$vbLabelText   $csharpLabel

下面是一个综合示例,展示了移除密码保护的完整工作流程:

using IronXL;

// First, open the protected workbook with the correct password
WorkBook protectedWorkBook = WorkBook.Load("encrypted_report.xlsx", "CurrentPassword123");

// Perform any necessary operations
WorkSheet sheet = protectedWorkBook.DefaultWorkSheet;
sheet["A1"].Value = "Updated after removing protection";

// Remove the password protection
protectedWorkBook.Password = null;

// Save the workbook without password protection
protectedWorkBook.SaveAs("unprotected_report.xlsx");

Console.WriteLine("Password protection removed successfully!");
using IronXL;

// First, open the protected workbook with the correct password
WorkBook protectedWorkBook = WorkBook.Load("encrypted_report.xlsx", "CurrentPassword123");

// Perform any necessary operations
WorkSheet sheet = protectedWorkBook.DefaultWorkSheet;
sheet["A1"].Value = "Updated after removing protection";

// Remove the password protection
protectedWorkBook.Password = null;

// Save the workbook without password protection
protectedWorkBook.SaveAs("unprotected_report.xlsx");

Console.WriteLine("Password protection removed successfully!");
$vbLabelText   $csharpLabel

何时应移除密码保护?

删除密码的常见情况包括

  • 存档:将文件移动到安全存储中,文件级加密是多余的
  • System Integration: When automated processes need to import Excel data without manual intervention
  • 协作:与不需要密码访问的团队成员共享文件
  • 迁移:将受保护的文件转换到不支持 Excel 加密的系统中使用

在从任何工作簿中移除密码保护之前,请务必确保您已获得适当授权。

IronXL provides the ability to protect and unprotect Excel workBooks and workSheets with a single line of C# code. For more advanced Excel security features, explore our guides on workbook metadata management and secure data handling practices.

常见问题解答

如何用 C# 对 Excel 工作簿进行密码保护?

使用 IronXL.Excel,您可以使用 Encrypt 方法对 Excel 工作簿进行密码保护。只需加载工作簿,调用 wb.Encrypt("YourPassword"),然后保存文件即可。只需调用一个方法,就能立即保护 Excel 文件的安全,而无需 Microsoft Office Interop。

我能在不知道密码的情况下打开密码保护的 Excel 文件吗?

不,IronXL.Excel 需要正确的密码才能打开受保护的 Excel 文件。在加载受密码保护的工作簿时,必须将密码作为第二个参数提供:WorkBook.Load("file.xlsx", "password")。如果没有正确的密码,则无法访问文件。

如果我试图用错误的密码打开受保护的工作簿,会发生什么情况?

当提供的密码不正确时,IronXL 会抛出异常,而不是返回空值或空工作簿。这一安全功能可防止未经授权的访问尝试。请务必在 try-catch 块中封装受密码保护的工作簿操作,以便从容应对身份验证失败。

如何在打开 Excel 文件之前检查该文件是否受密码保护?

Excel 的文件格式不允许在不尝试打开文件的情况下检查密码保护状态。对于 IronXL,推荐的方法是先尝试加载没有密码的文件,然后捕获异常,必要时使用密码重试。

能否从 Excel 工作簿中移除密码保护?

是的,IronXL 允许您从工作簿中移除密码保护。首先,使用 WorkBook.Load("file.xlsx", "password"),用正确的密码加载受保护的工作簿,然后不加密保存,以创建不受保护的版本。

密码保护是否适用于所有 Excel 文件格式?

IronXL 支持现代 Excel 格式的密码保护,包括 .xlsx 和 .xlsm 文件。该加密功能可在不同版本的 Excel 中无缝运行,无需在系统中安装 Microsoft Office。

Curtis Chau
技术作家

Curtis Chau 拥有卡尔顿大学的计算机科学学士学位,专注于前端开发,精通 Node.js、TypeScript、JavaScript 和 React。他热衷于打造直观且美观的用户界面,喜欢使用现代框架并创建结构良好、视觉吸引力强的手册。

除了开发之外,Curtis 对物联网 (IoT) 有浓厚的兴趣,探索将硬件和软件集成的新方法。在空闲时间,他喜欢玩游戏和构建 Discord 机器人,将他对技术的热爱与创造力相结合。

准备开始了吗?
Nuget 下载 1,913,565 | 版本: 2026.3 刚刚发布
Still Scrolling Icon

还在滚动吗?

想快速获得证据? PM > Install-Package IronXL.Excel
运行示例 观看您的数据变成电子表格。