如何在 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 工作表套用唯讀保護,防止未經授權的修改,同時允許使用者查看內容。

快速入門:用一行程式碼保護工作表

使用 IronXL,您可以透過呼叫ProtectSheet方法將任何工作表設為唯讀——只需一行程式碼即可立即保護工作表。 非常適合希望在 C# 中輕鬆實現安全防護的開發人員。

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

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

    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") 。 這將為選定的工作表設定基於密碼的唯讀身份驗證。

: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();
$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");
$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");
$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();
$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");
$vbLabelText   $csharpLabel

工作表保護最佳實踐

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

1.使用強密碼:產生包含字母、數字和特殊字元的複雜密碼。 考慮使用密碼管理器或安全儲存來管理多個工作表密碼。

2.文件保護狀態:記錄哪些工作表受到保護以及保護的原因。 這有助於維護和故障排除。

  1. 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");
$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.Excel 的 ProtectSheet 方法在 C# 中對 Excel 工作表進行密碼保護。只需在任何工作表物件上呼叫 workSheet.ProtectSheet("YourPassword")。這會套用唯讀保護,防止未經授權的修改,同時允許使用者檢視內容。

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

是的,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擁有卡爾頓大學電腦科學學士學位,專長於前端開發,精通Node.js、TypeScript、JavaScript和React。他熱衷於打造直覺美觀的使用者介面,喜歡使用現代框架,並擅長撰寫結構清晰、視覺效果出色的使用者手冊。

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

準備好開始了嗎?
Nuget 下載 1,802,965 | 版本: 2025.12 剛剛發布