保護 Excel 檔案

IronXL 的Encrypt方法使開發人員能夠對整個 Excel 工作簿和單一工作表套用密碼保護。 此功能對於保護敏感資料至關重要,並確保只有授權使用者才能存取或修改 Excel 檔案的內容。

IronXL 還允許進行工作表層級的保護,從而防止使用者編輯工作簿的某些部分或特定工作表。 這在協作環境中尤其有用,因為你可能希望限制編輯權限,但仍然允許使用者查看資料或與資料互動。 此外,無論是否使用密碼,都可以選擇移除保護,這提供了靈活性,使其既適用於安全環境,也適用於需要暫時恢復存取權限的情況。 總而言之,此功能是確保自動化資料處理工作流程中 Excel 檔案安全的重要工具。

在這段程式碼中,首先使用 IronXL 的WorkBook.Load()方法從檔案sample.xlsx載入工作簿。 工作簿載入後,使用Encrypt()方法對整個工作簿套用密碼保護,密碼設定為myP@ssw0rd 。 這樣可以確保沒有正確的密碼就無法開啟或修改工作簿。

Next, the default worksheet of the workbook is accessed using the DefaultWorkSheet property. The ProtectSheet() method is then called on this worksheet, applying a password code>("myP@ssw0rd_sheet") that restricts editing on the sheet level. 這樣可以防止使用者在未提供正確密碼的情況下對受保護的工作表進行更改。

Finally, the Save() method is invoked to save the changes made to both the workbook and the worksheet, ensuring that the protection settings are preserved in the saved file. This ensures that the workbook and its worksheet are both securely protected and can only be accessed or modified with the respective passwords.

學習如何在 C# 中為 Excel 工作簿設定密碼

準備好開始了嗎?
Nuget 下載 1,765,830 | 版本: 2025.12 剛發表