如何在 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會拋出異常,而不是傳回 null 或空白工作簿。 這種行為透過阻止未經授權的存取嘗試來確保安全性。始終將受密碼保護的工作簿操作放在 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 會產生異常,而不是回傳 null 或一個空的工作簿。此安全功能可防止未經授權的存取嘗試。請務必將密碼保護的工作簿操作包裝在 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 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。

除了開發之外,Curtis 對物聯網 (IoT) 有著濃厚的興趣,探索將硬體和軟體結合的創新方式。在閒暇時間,他喜愛遊戲並構建 Discord 機器人,結合科技與創意的樂趣。

A PHP Error was encountered

Severity: Notice

Message: Undefined index: IronXl.Excel

Filename: helpers/counter_helper.php

Line Number: 85

Backtrace:

File: /var/www/ironpdf.com/application/helpers/counter_helper.php
Line: 85
Function: _error_handler

File: /var/www/ironpdf.com/application/views/main/sections/ready_to_started_202509.php
Line: 12
Function: getTotalDonwloadNumber

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 489
Function: view

File: /var/www/ironpdf.com/application/controllers/Products/Howto.php
Line: 31
Function: render_products_view

File: /var/www/ironpdf.com/index.php
Line: 292
Function: require_once

A PHP Error was encountered

Severity: Notice

Message: Undefined index: IronXl.Excel

Filename: helpers/counter_helper.php

Line Number: 85

Backtrace:

File: /var/www/ironpdf.com/application/helpers/counter_helper.php
Line: 85
Function: _error_handler

File: /var/www/ironpdf.com/application/views/main/sections/ready_to_started_202509.php
Line: 19
Function: getTotalDonwloadNumber

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 489
Function: view

File: /var/www/ironpdf.com/application/controllers/Products/Howto.php
Line: 31
Function: render_products_view

File: /var/www/ironpdf.com/index.php
Line: 292
Function: require_once

準備好開始了嗎?
Nuget 下載 1,890,100 | 版本: 2026.3 剛剛發布

A PHP Error was encountered

Severity: Notice

Message: Undefined index: IronXl.Excel

Filename: helpers/counter_helper.php

Line Number: 85

Backtrace:

File: /var/www/ironpdf.com/application/helpers/counter_helper.php
Line: 85
Function: _error_handler

File: /var/www/ironpdf.com/application/views/main/sections/still_scrolling_202512.php
Line: 17
Function: getTotalDonwloadNumber

File: /var/www/ironpdf.com/application/views/products/sections/three_column_docs_page_structure.php
Line: 71
Function: view

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 88
Function: view

File: /var/www/ironpdf.com/application/views/products/how-to/index.php
Line: 2
Function: view

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 88
Function: view

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 552
Function: view

File: /var/www/ironpdf.com/application/controllers/Products/Howto.php
Line: 31
Function: render_products_view

File: /var/www/ironpdf.com/index.php
Line: 292
Function: require_once

A PHP Error was encountered

Severity: Notice

Message: Undefined index: IronXl.Excel

Filename: helpers/counter_helper.php

Line Number: 85

Backtrace:

File: /var/www/ironpdf.com/application/helpers/counter_helper.php
Line: 85
Function: _error_handler

File: /var/www/ironpdf.com/application/views/main/sections/still_scrolling_202512.php
Line: 24
Function: getTotalDonwloadNumber

File: /var/www/ironpdf.com/application/views/products/sections/three_column_docs_page_structure.php
Line: 71
Function: view

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 88
Function: view

File: /var/www/ironpdf.com/application/views/products/how-to/index.php
Line: 2
Function: view

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 88
Function: view

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 552
Function: view

File: /var/www/ironpdf.com/application/controllers/Products/Howto.php
Line: 31
Function: render_products_view

File: /var/www/ironpdf.com/index.php
Line: 292
Function: require_once

Still Scrolling Icon

還在捲動嗎?

想要快速證明? PM > Install-Package IronXl.Excel
執行範例 觀看您的資料變成試算表。