如何在 C# 中為工作簿設定密碼
IronXL 讓開發人員能透過單一方法呼叫,在 C# 中為 Excel 工作簿設定密碼保護——使用 Encrypt 方法並輸入您指定的密碼,儲存工作簿即可立即套用保護。
快速入門:使用 IronXL 為工作簿設定密碼
只需一個簡單步驟,IronXL 即可讓開發人員加密 Excel 工作簿——無需 Interop,輕鬆無煩惱。 請使用 Encrypt 方法並輸入您的密碼,儲存檔案即可立即保護您的工作簿。
如何存取受密碼保護的工作簿?
若要開啟受保護的試算表,可將密碼作為第二個參數傳遞給 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}");
}
Imports IronXL
' Attempt to open a password-protected workbook
Try
Dim protectedWorkBook As WorkBook = WorkBook.Load("encrypted_data.xlsx", "MySecretPass123!")
' Access the first worksheet
Dim sheet As WorkSheet = protectedWorkBook.WorkSheets(0)
' Read data from protected file
Dim cellValue = sheet("A1").Value
Console.WriteLine($"Successfully accessed protected workbook. A1 contains: {cellValue}")
Catch ex As Exception
Console.WriteLine($"Failed to open workbook: {ex.Message}")
End Try
如果我輸入錯誤的密碼會發生什麼事?
當輸入錯誤的密碼時,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();
Dim workBook As WorkBook = WorkBook.Load("sample.xlsx")
' Open protected spreadsheet file
Dim protectedWorkBook As WorkBook = WorkBook.Load("sample.xlsx", "IronSoftware")
' Set protection for spreadsheet file
workBook.Encrypt("IronSoftware")
workBook.Save()
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!");
Imports IronXL
Imports System
' Create a new workbook with sensitive financial data
Dim workBook As WorkBook = WorkBook.Create(ExcelFileFormat.XLSX)
Dim sheet As WorkSheet = 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!")
為何密碼必須儲存後才會生效?
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();
' Load workbook
Dim workBook As 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()
如何從工作簿中移除密碼?
若要移除試算表的密碼,只需將 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;
' Remove protection for opened workbook. Original password is required.
workBook.Password = Nothing
以下是一個完整的範例,展示移除密碼保護的完整工作流程:
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!");
Imports IronXL
' First, open the protected workbook with the correct password
Dim protectedWorkBook As WorkBook = WorkBook.Load("encrypted_report.xlsx", "CurrentPassword123")
' Perform any necessary operations
Dim sheet As WorkSheet = protectedWorkBook.DefaultWorkSheet
sheet("A1").Value = "Updated after removing protection"
' Remove the password protection
protectedWorkBook.Password = Nothing
' Save the workbook without password protection
protectedWorkBook.SaveAs("unprotected_report.xlsx")
Console.WriteLine("Password protection removed successfully!")
何時應移除密碼保護?
移除密碼的常見情境包括:
- 歸檔:將檔案移至安全的儲存空間,此處無需進行檔案層級的加密
- System Integration: When automated processes need to import Excel data without manual intervention
- 協作:與無需密碼存取權限的團隊成員共享檔案
- 遷移:將受保護的檔案轉換為可在不支援 Excel 加密功能的系統中使用的格式
在移除任何工作簿的密碼保護之前,請務必確認您已獲得適當授權。
IronXL 提供透過單行 C# 程式碼即可保護及解除 Excel workBooks 與 workSheets 保護的功能。 For more advanced Excel security features, explore our guides on workbook metadata management and secure data handling practices.
常見問題
如何在 C# 中為 Excel 工作簿設定密碼保護?
透過 IronXL,您可以使用 Encrypt 方法為 Excel 工作簿設定密碼保護。只需載入工作簿,呼叫 wb.Encrypt("您的密碼"),然後儲存檔案即可。這單一的方法呼叫能立即保護您的 Excel 檔案,且無需 Microsoft Office Interop。
我可以在不知道密碼的情況下開啟受密碼保護的 Excel 檔案嗎?
不,IronXL 需要正確的密碼才能開啟受保護的 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。

