19. 工作表 / 工作簿保护¶
本章介绍工作表保护与工作簿保护,含可选密码(SHA-512 + salt 哈希)。
Warning
工作表 / 工作簿保护支持 xlsx / xlsm / xlsb 写出与读回。xls / csv 不支持,写出时经 OnDegradation 上报。
19.1 工作表保护 SheetProtection¶
Worksheet.Protection 控制受保护工作表中允许 / 禁止的操作,可选密码(SHA-512 + salt 哈希):
var ws = Excel.Create().Worksheets["Sheet1"];
var p = new SheetProtection
{
Enabled = true,
// 允许的操作(默认 false 表示禁止):
SelectLockedCells = true,
SelectUnlockedCells = true,
// FormatCells / FormatColumns / FormatRows / InsertColumns / InsertRows /
// InsertHyperlinks / DeleteColumns / DeleteRows / Sort / AutoFilter / PivotTables
Objects = true, // 默认 true 允许编辑对象
Scenarios = true, // 默认 true 允许编辑方案
};
p.SetPassword("protect123"); // 可选密码(方法,不能写在 initializer 里)
ws.Protection = p;
读回:
var opened = Excel.Open("protected.xlsx");
var p = opened.Worksheets[0].Protection;
if (p is not null)
{
Console.WriteLine(p.Enabled);
Console.WriteLine(p.HasPassword);
Console.WriteLine(p.VerifyPassword("protect123")); // 对从文件读取的哈希有效
p.RemovePassword(); // 移除保护密码(null/空白同样视为移除)
}
SheetProtection 参数:
| 参数 | 类型 | 说明 |
|---|---|---|
Enabled |
bool |
是否启用保护(写出 sheetProtection 的前提) |
SelectLockedCells / SelectUnlockedCells |
bool |
是否允许选定锁定 / 未锁定单元格(默认 true) |
Objects / Scenarios |
bool |
是否允许编辑对象 / 方案(默认 true) |
FormatCells…PivotTables |
bool |
允许的编辑操作(默认 false 禁止) |
SetPassword / RemovePassword |
方法 | 设置 / 移除保护密码(null / 空白视为移除) |
VerifyPassword |
方法 | 验证密码(仅对从文件读取的哈希有效) |
输出:
⚠️ 读回时
HasPassword恒为False。密码以 SHA-512 + salt 哈希落盘,库不把明文读回内存。是否设保护密码应通过VerifyPassword(...)判断,而不是HasPassword。
19.2 工作簿保护 WorkbookProtection¶
Workbook.Protection 锁定工作簿结构 / 窗口,可选密码:
var wb = Excel.Create();
var p2 = new WorkbookProtection
{
Enabled = true,
LockStructure = true, // 禁止插入/删除/移动/隐藏/重命名工作表
LockWindows = false,
};
p2.SetPassword("wbpass"); // 可选密码(方法,不能写在 initializer 里)
wb.Protection = p2;
wb.SaveAs("wbprotected.xlsx");
读回:
var opened = Excel.Open("wbprotected.xlsx");
var p = opened.Protection;
if (p is not null)
Console.WriteLine($"{p.Enabled} structure={p.LockStructure} hasPwd={p.HasPassword}");
WorkbookProtection 参数:
| 参数 | 类型 | 说明 |
|---|---|---|
Enabled |
bool |
是否启用保护(写出 workbookProtection 的前提) |
LockStructure |
bool |
禁止插入 / 删除 / 移动 / 隐藏 / 重命名工作表(默认 true) |
LockWindows |
bool |
锁定窗口(默认 false) |
SetPassword / RemovePassword |
方法 | 设置 / 移除保护密码(null / 空白视为移除) |
VerifyPassword |
方法 | 验证密码(仅对从文件读取的哈希有效) |
输出:
⚠️ 同 19.1:读回的
hasPwd=False不代表未设密码。密码明文不入内存,用VerifyPassword判断。