如何在 C# 中為 Excel 工作表設定密碼

如何在 C# 中為工作表設定密碼

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

若要在 C# 中為工作表設定密碼保護,請使用 IronXL 的 ProtectSheet 方法,並傳入如 workSheet.ProtectSheet("MyPass123") 這樣的密碼參數。 此功能會對任何 Excel 工作表套用唯讀保護,在防止未經授權修改的同時,仍允許使用者檢視內容。

快速入門:僅需一行程式碼即可保護工作表

Using IronXL,您只需呼叫 ProtectSheet 方法,即可將任何工作表設為唯讀——僅需一行程式碼,即可立即保護工作表的安全。 非常適合希望在 C# 中輕鬆實現保護功能的開發者。

  1. using NuGet 套件管理員安裝 https://www.nuget.org/packages/IronXL.Excel

    PM > Install-Package IronXL.Excel
  2. 請複製並執行此程式碼片段。

    new IronXl.WorkBook("data.xlsx").DefaultWorkSheet.ProtectSheet("MyPass123");
  3. 部署至您的生產環境進行測試

    立即透過免費試用,在您的專案中開始使用 IronXL

    arrow pointer

開始使用 IronXL


如何存取受密碼保護的工作表?

IronXL 讓您無需密碼即可存取並修改任何受保護的工作表。 一旦使用 IronXL 開啟試算表,您即可修改任何工作表中的任何儲存格。 This capability is particularly useful when you need to load existing spreadsheets that may have protection applied by other users or systems.

在處理受保護的工作表時,IronXL 能無縫處理底層的安全性。 You can open Excel worksheets that are password-protected and perform operations like reading data, updating cells, or applying formulas without needing to know the original password. 這使得 IronXL 成為需要處理多個受保護檔案的自動化資料處理情境中的絕佳選擇。

如何對工作表套用密碼保護?

若要限制工作表的修改權限,同時允許使用者在 Excel 中檢視其內容,請使用 ProtectSheet 方法,並將密碼作為參數傳入。 例如,workSheet.ProtectSheet("IronXL")。 此設定將為選定的工作表建立基於密碼的 ReadOnly 驗證機制。

:path=/static-assets/excel/content-code-examples/how-to/set-password-worksheet-protect.cs
using IronXL;

WorkBook workBook = WorkBook.Load("sample.xlsx");
WorkSheet workSheet = workBook.DefaultWorkSheet;

// Set protection for selected worksheet
workSheet.ProtectSheet("IronXL");

workBook.Save();
Imports IronXL

Private workBook As WorkBook = WorkBook.Load("sample.xlsx")
Private workSheet As WorkSheet = workBook.DefaultWorkSheet

' Set protection for selected worksheet
workSheet.ProtectSheet("IronXL")

workBook.Save()
$vbLabelText   $csharpLabel

保護多個工作表

當處理包含多個工作表的複雜工作簿時,您可能需要採用不同的保護策略:

using IronXL;

// Load the workbook
WorkBook workBook = WorkBook.Load("financial-report.xlsx");

// Protect each worksheet with a different password
workBook.GetWorkSheet("Summary").ProtectSheet("SummaryPass123");
workBook.GetWorkSheet("Details").ProtectSheet("DetailsSecure456");
workBook.GetWorkSheet("Charts").ProtectSheet("ChartsProtect789");

// Save the workbook with all protections applied
workBook.SaveAs("protected-financial-report.xlsx");
using IronXL;

// Load the workbook
WorkBook workBook = WorkBook.Load("financial-report.xlsx");

// Protect each worksheet with a different password
workBook.GetWorkSheet("Summary").ProtectSheet("SummaryPass123");
workBook.GetWorkSheet("Details").ProtectSheet("DetailsSecure456");
workBook.GetWorkSheet("Charts").ProtectSheet("ChartsProtect789");

// Save the workbook with all protections applied
workBook.SaveAs("protected-financial-report.xlsx");
Imports IronXL

' Load the workbook
Dim workBook As WorkBook = WorkBook.Load("financial-report.xlsx")

' Protect each worksheet with a different password
workBook.GetWorkSheet("Summary").ProtectSheet("SummaryPass123")
workBook.GetWorkSheet("Details").ProtectSheet("DetailsSecure456")
workBook.GetWorkSheet("Charts").ProtectSheet("ChartsProtect789")

' Save the workbook with all protections applied
workBook.SaveAs("protected-financial-report.xlsx")
$vbLabelText   $csharpLabel

This approach is particularly useful when managing worksheets that contain different levels of sensitive information. You can also combine worksheet protection with workbook-level password protection for enhanced security.

當使用者嘗試開啟受保護的工作表時會發生什麼情況?

Code editor showing Excel worksheet protection implementation with IronXL library and file explorer displaying .xlsx files

當使用者嘗試修改 Excel 中受保護的工作表時,系統會提示輸入密碼。 若未輸入正確密碼,使用者僅能瀏覽內容,無法進行任何修改。 此保護機制在不同版本的 Excel 以及其他支援 Excel 格式的試算表應用程式中均有效。

在不同情境下處理受保護的工作表

IronXL 的工作表保護功能可與其他 Excel 操作無縫整合。 You can still perform read operations, extract data, and even convert the file to different formats while maintaining the protection status.

using IronXL;

// Load a workbook and protect specific worksheets based on content
WorkBook workBook = WorkBook.Load("employee-data.xlsx");

foreach (WorkSheet sheet in workBook.WorkSheets)
{
    // Check if the sheet name contains sensitive keywords
    if (sheet.Name.Contains("Salary") || sheet.Name.Contains("Personal"))
    {
        // Apply stronger password protection to sensitive sheets
        sheet.ProtectSheet($"Secure_{sheet.Name}_2024!");
    }
    else
    {
        // Apply standard protection to other sheets
        sheet.ProtectSheet("StandardProtection");
    }
}

// Save the selectively protected workbook
workBook.SaveAs("employee-data-protected.xlsx");
using IronXL;

// Load a workbook and protect specific worksheets based on content
WorkBook workBook = WorkBook.Load("employee-data.xlsx");

foreach (WorkSheet sheet in workBook.WorkSheets)
{
    // Check if the sheet name contains sensitive keywords
    if (sheet.Name.Contains("Salary") || sheet.Name.Contains("Personal"))
    {
        // Apply stronger password protection to sensitive sheets
        sheet.ProtectSheet($"Secure_{sheet.Name}_2024!");
    }
    else
    {
        // Apply standard protection to other sheets
        sheet.ProtectSheet("StandardProtection");
    }
}

// Save the selectively protected workbook
workBook.SaveAs("employee-data-protected.xlsx");
Imports IronXL

' Load a workbook and protect specific worksheets based on content
Dim workBook As WorkBook = WorkBook.Load("employee-data.xlsx")

For Each sheet As WorkSheet In workBook.WorkSheets
    ' Check if the sheet name contains sensitive keywords
    If sheet.Name.Contains("Salary") OrElse sheet.Name.Contains("Personal") Then
        ' Apply stronger password protection to sensitive sheets
        sheet.ProtectSheet($"Secure_{sheet.Name}_2024!")
    Else
        ' Apply standard protection to other sheets
        sheet.ProtectSheet("StandardProtection")
    End If
Next

' Save the selectively protected workbook
workBook.SaveAs("employee-data-protected.xlsx")
$vbLabelText   $csharpLabel

如何移除工作表的密碼保護?

若要從特定工作表中移除密碼,請使用 UnprotectSheet 方法。 只需呼叫 workSheet.UnprotectSheet() 即可移除工作表相關的任何密碼。

:path=/static-assets/excel/content-code-examples/how-to/set-password-worksheet-unprotect.cs
// Remove protection for selected worksheet. It works without password!
workSheet.UnprotectSheet();
' Remove protection for selected worksheet. It works without password!
workSheet.UnprotectSheet()
$vbLabelText   $csharpLabel

工作表批次解除保護

當處理多個受保護的工作表時,您可能需要一次解除所有工作表的保護。 以下是一種高效的翻譯方法:

using IronXL;
using System;

// Load the protected workbook
WorkBook workBook = WorkBook.Load("multi-protected.xlsx");

// Counter for tracking operations
int unprotectedCount = 0;

// Iterate through all worksheets and remove protection
foreach (WorkSheet sheet in workBook.WorkSheets)
{
    try
    {
        sheet.UnprotectSheet();
        unprotectedCount++;
        Console.WriteLine($"Unprotected: {sheet.Name}");
    }
    catch (Exception ex)
    {
        Console.WriteLine($"Failed to unprotect {sheet.Name}: {ex.Message}");
    }
}

Console.WriteLine($"Successfully unprotected {unprotectedCount} worksheets");

// Save the unprotected workbook
workBook.SaveAs("multi-unprotected.xlsx");
using IronXL;
using System;

// Load the protected workbook
WorkBook workBook = WorkBook.Load("multi-protected.xlsx");

// Counter for tracking operations
int unprotectedCount = 0;

// Iterate through all worksheets and remove protection
foreach (WorkSheet sheet in workBook.WorkSheets)
{
    try
    {
        sheet.UnprotectSheet();
        unprotectedCount++;
        Console.WriteLine($"Unprotected: {sheet.Name}");
    }
    catch (Exception ex)
    {
        Console.WriteLine($"Failed to unprotect {sheet.Name}: {ex.Message}");
    }
}

Console.WriteLine($"Successfully unprotected {unprotectedCount} worksheets");

// Save the unprotected workbook
workBook.SaveAs("multi-unprotected.xlsx");
Imports IronXL
Imports System

' Load the protected workbook
Dim workBook As WorkBook = WorkBook.Load("multi-protected.xlsx")

' Counter for tracking operations
Dim unprotectedCount As Integer = 0

' Iterate through all worksheets and remove protection
For Each sheet As WorkSheet In workBook.WorkSheets
    Try
        sheet.UnprotectSheet()
        unprotectedCount += 1
        Console.WriteLine($"Unprotected: {sheet.Name}")
    Catch ex As Exception
        Console.WriteLine($"Failed to unprotect {sheet.Name}: {ex.Message}")
    End Try
Next

Console.WriteLine($"Successfully unprotected {unprotectedCount} worksheets")

' Save the unprotected workbook
workBook.SaveAs("multi-unprotected.xlsx")
$vbLabelText   $csharpLabel

工作表保護的最佳實務

在 C# 應用程式中實作工作表保護時,請參考以下建議:

  1. 使用強密碼:建立結合字母、數字和特殊字元的複雜密碼。 建議使用密碼管理工具或安全儲存方案來管理多個試算表的密碼。

  2. 文件保護狀態:記錄哪些工作表已受保護及其原因。 這有助於後續的維護與故障排除。

  3. Combine with License Management: When distributing protected Excel files, ensure you have properly configured your IronXL license for deployment scenarios.

  4. 測試保護情境:在部署受保護的工作表之前,請使用各種 Excel 版本進行測試,以確保相容性。

  5. 考量效能:雖然保護功能不會對效能造成顯著影響,但在大型工作簿中處理大量受保護的工作表時,可能需要採取優化策略。

進階防護情境

IronXL 的工作表保護功能可整合至更複雜的工作流程中。 For instance, you can create new spreadsheets with pre-configured protection settings:

using IronXL;
using System;

// Create a new workbook with protected templates
WorkBook workBook = WorkBook.Create();

// Add and configure protected worksheets
WorkSheet budgetSheet = workBook.CreateWorkSheet("Budget2024");
budgetSheet["A1"].Value = "Annual Budget";
budgetSheet["A2"].Value = "Department";
budgetSheet["B2"].Value = "Allocated Amount";
// Add more data...
budgetSheet.ProtectSheet("BudgetProtect2024");

WorkSheet forecastSheet = workBook.CreateWorkSheet("Forecast");
forecastSheet["A1"].Value = "Revenue Forecast";
// Add forecast data...
forecastSheet.ProtectSheet("ForecastSecure123");

// Save the protected workbook
workBook.SaveAs("protected-templates.xlsx");
using IronXL;
using System;

// Create a new workbook with protected templates
WorkBook workBook = WorkBook.Create();

// Add and configure protected worksheets
WorkSheet budgetSheet = workBook.CreateWorkSheet("Budget2024");
budgetSheet["A1"].Value = "Annual Budget";
budgetSheet["A2"].Value = "Department";
budgetSheet["B2"].Value = "Allocated Amount";
// Add more data...
budgetSheet.ProtectSheet("BudgetProtect2024");

WorkSheet forecastSheet = workBook.CreateWorkSheet("Forecast");
forecastSheet["A1"].Value = "Revenue Forecast";
// Add forecast data...
forecastSheet.ProtectSheet("ForecastSecure123");

// Save the protected workbook
workBook.SaveAs("protected-templates.xlsx");
Imports IronXL
Imports System

' Create a new workbook with protected templates
Dim workBook As WorkBook = WorkBook.Create()

' Add and configure protected worksheets
Dim budgetSheet As WorkSheet = workBook.CreateWorkSheet("Budget2024")
budgetSheet("A1").Value = "Annual Budget"
budgetSheet("A2").Value = "Department"
budgetSheet("B2").Value = "Allocated Amount"
' Add more data...
budgetSheet.ProtectSheet("BudgetProtect2024")

Dim forecastSheet As WorkSheet = workBook.CreateWorkSheet("Forecast")
forecastSheet("A1").Value = "Revenue Forecast"
' Add forecast data...
forecastSheet.ProtectSheet("ForecastSecure123")

' Save the protected workbook
workBook.SaveAs("protected-templates.xlsx")
$vbLabelText   $csharpLabel

For comprehensive Excel file manipulation capabilities, explore the complete IronXL documentation or check out tutorials on reading Excel files to expand your Excel automation toolkit.

IronXL allows you to protect and unprotect any Excel workbook and worksheet with a single line of C# code.

常見問題

如何在 C# 中為 Excel 工作表設定密碼保護?

您可透過 IronXL 的 ProtectSheet 方法,使用 C# 為 Excel 工作表設定密碼保護。只需在任何工作表物件上呼叫 workSheet.ProtectSheet("您的密碼") 即可。此操作將套用唯讀保護,在允許使用者檢視內容的同時,防止未經授權的修改。

我可以在不知道密碼的情況下存取並修改受密碼保護的工作表嗎?

是的,IronXL 允許您在無需原始密碼的情況下存取並修改任何受保護的工作表。一旦使用 IronXL 開啟試算表,您即可修改任何工作表中的任何儲存格,這使其非常適合需要處理多個受保護檔案的自動化資料處理情境。

ProtectSheet 方法適用何種保護類型?

IronXL 中的 ProtectSheet 方法會對選定的工作表套用唯讀驗證。這表示使用者在 Excel 中開啟檔案時,雖然可以檢視內容,但若未輸入正確密碼則無法進行修改。

我可以為多個工作表設定不同的密碼進行保護嗎?

是的,IronXL 允許您使用獨特的密碼保護多個工作表。您可以遍歷工作簿中的工作表,並透過 ProtectSheet 方法為每個工作表設定不同的密碼,例如:workBook.GetWorkSheet("Summary").ProtectSheet("SummaryPass123")。

要透過程式碼保護 Excel 試算表,最簡單的方法是什麼?

最簡單的方法是使用 IronXL 的單行程式碼方式:new IronXl.WorkBook("data.xlsx").DefaultWorkSheet.ProtectSheet("MyPass123")。這將立即透過密碼保護來鎖定預設工作表。

密碼保護會影響將工作表匯出為不同格式的功能嗎?

不,IronXL 中的密碼保護功能不會阻止您將工作表匯出為不同的試算表格式。即使已套用密碼保護,您仍可將受保護的工作表儲存並匯出為各種 Excel 格式。

Curtis Chau
技術撰稿人

Curtis Chau 擁有卡爾頓大學(Carleton University)的電腦科學學士學位,專精於前端開發,並精通 Node.js、TypeScript、JavaScript 及 React。他熱衷於打造直觀且美觀的用戶介面,喜歡運用現代框架,並創建結構完善、視覺上吸引人的手冊。

除了開發工作之外,Curtis 對物聯網(IoT)抱有濃厚興趣,致力於探索整合硬體與軟體的創新方法。閒暇時,他喜歡玩遊戲和開發 Discord 機器人,將對科技的熱愛與創意相結合。

準備開始了嗎?
Nuget 下載 2,052,917 | 版本: 2026.6 just released
Still Scrolling Icon

還在捲動嗎?

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