gpt4 book ai didi

c# - 如何使用 Open XML 密码保护 Excel 文档

转载 作者:太空狗 更新时间:2023-10-29 23:20:44 27 4
gpt4 key购买 nike

目前,我正在通过传递 MemoryStream 参数,使用 Open XML 的 SpreadsheetDocument 类创建一个新的 Excel 文档。我现在需要为此 SpreadsheetDocument 对象设置密码,但我尝试的操作似乎不起作用。无需输入密码即可打开 Excel 文档。下面是我到目前为止尝试过的(memMemoryStream 参数):

using (SpreadsheetDocument spreadsheet = SpreadsheetDocument.Open(mem, true))
{
foreach (var sheet in spreadsheet.WorkbookPart.WorksheetParts)
{
sheet.Worksheet.Append(new SheetProtection() { Password = "test" });
}
}

我也尝试过以下但没有成功:

using (SpreadsheetDocument spreadsheet = SpreadsheetDocument.Open(mem, true))
{
spreadsheet.WorkbookPart.Workbook.WorkbookProtection = new WorkbookProtection
{
LockStructure = true,
LockWindows = true,
WorkbookPassword = "test"
}
}

请问我错过了什么?

最佳答案

Openxml sheet protect Password 输入数据类型为“HexBinaryValue”。因此输入的密码将从字符串转换为十六进制。

foreach (var worksheetPart in spreadsheet.WorkbookPart.WorksheetParts)
{
//Call the method to convert the Password string "MyPasswordfor sheet" to hexbinary type
string hexConvertedPassword = HexPasswordConversion("MyPasswordfor sheet");
//passing the Converted password to sheet protection
SheetProtection sheetProt = new SheetProtection() { Sheet = true, Objects = true, Scenarios = true, Password = hexConvertedPassword };
worksheetPart.Worksheet.InsertAfter(sheetProt,worksheetPart.Worksheet.Descendants<SheetData>().LastOrDefault());
worksheetPart.Worksheet.Save();
}


/* This method will convert the string password to hexabinary value */
protected string HexPasswordConversion(string password)
{
byte[] passwordCharacters = System.Text.Encoding.ASCII.GetBytes(password);
int hash = 0;
if (passwordCharacters.Length > 0)
{
int charIndex = passwordCharacters.Length;

while (charIndex-- > 0)
{
hash = ((hash >> 14) & 0x01) | ((hash << 1) & 0x7fff);
hash ^= passwordCharacters[charIndex];
}
// Main difference from spec, also hash with charcount
hash = ((hash >> 14) & 0x01) | ((hash << 1) & 0x7fff);
hash ^= passwordCharacters.Length;
hash ^= (0x8000 | ('N' << 8) | 'K');
}

return Convert.ToString(hash, 16).ToUpperInvariant();
}

关于c# - 如何使用 Open XML 密码保护 Excel 文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39449653/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com