密码保护生成的Excel工作表

时间:2014-09-24 08:54:34

标签: c# excel openxml password-protection spreadsheetlight

我的代码生成一个OpenXML电子表格,我想防止修改和删除操作。我的解决方案似乎有效,但我发现在Excel中打开它,在"评论"小组我可以推动" Unprotect"按钮和Excel取消保护所选工作表而不询问任何密码。我怎么能避免这个?

String password = Guid.NewGuid().ToString().Replace("-", string.Empty).Substring(0, 16);

using (SpreadsheetDocument excelDoc = SpreadsheetDocument.Open(input, true))
{
    foreach (WorksheetPart worksheetPart in excelDoc.WorkbookPart.WorksheetParts)
    {
        SheetProtection sp = new SheetProtection()
        {
            Sheet = true,
            SelectLockedCells = false,
            SelectUnlockedCells = false,
            Password = password,
            Objects = true,
            Scenarios = true,
            // AlgorithmName = "SHA-256"
        };
        foreach (OpenXmlElement currentChildElement in worksheetPart.Worksheet.ChildElements)
        {
            if (currentChildElement is SheetData)
            {
                worksheetPart.Worksheet.InsertAfter(sp, currentChildElement);
                worksheetPart.Worksheet.Save();
            }
        }
    }

0 个答案:

没有答案