如何在 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 方法加上您的密碼,並儲存檔案,以立即保護您的工作簿。

Nuget Icon立即開始使用 NuGet 建立 PDF 檔案:

  1. 使用 NuGet 套件管理器安裝 IronXL

    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.
請注意沒有正確的密碼,無法開啟受保護的電子表格
以下是一個完整的範例,示範如何存取受密碼保護的工作簿: ```csharp 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}"); } ```

如果我用錯密碼會怎樣? 當提供錯誤的密碼時,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`方法,如下面的程式碼所示: ```csharp :path=/static-assets/excel/content-code-examples/how-to/set-password-workbook-protect.cs ``` For more advanced scenarios, you can combine workbook encryption with worksheet-level protection: ```csharp 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!"); ```

為什麼密碼只有在儲存後才能生效? 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 支援工作簿層級和工作表層級的保護。 工作簿加密可防止未經授權的檔案存取,而工作表保護則可防止修改特定工作表。 您可以結合這兩種方法: ```csharp // 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(); ``` C# code showing WorkBook.Load() and WorkBook.Encrypt() methods with file explorer displaying Excel files

如何從工作簿中移除密碼? 要從電子表格中刪除密碼,只需將`Password`欄位設為 null,如下面的程式碼所示: [{i:(只有在存取工作簿後才能執行此操作。 因此,必須知道原始密碼。 ```csharp :path=/static-assets/excel/content-code-examples/how-to/set-password-workbook-unprotect.cs ``` 以下是一個全面的範例,顯示移除密碼保護的完整工作流程: ```csharp 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!"); ```

何時應該移除密碼保護? 移除密碼的常見情境包括 - **歸檔**:將檔案移至安全的儲存空間,其中檔案層級的加密是多餘的 - **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。

Chaknith Bin
軟體工程師
Chaknith 在 IronXL 和 IronBarcode 上工作。他對 C# 和 .NET 擁有深厚的專業知識,幫助改進了軟體並支持客戶。他從用戶互動中得到的見解有助於改善產品、文檔和整體體驗。
準備好開始了嗎?
Nuget 下載 1,765,830 | 版本: 2025.12 剛發表