使用EPPlus设置Excel工作表保护

3

我正在尝试使用EPPlus为XLSM文件设置工作表权限,但似乎我只能设置默认的保护级别,无法设置单个保护。为了记录,我正在尝试以编程方法1的方式完成 这篇文章中的内容。以下是我正在使用的代码:

using (var p = new ExcelPackage("output.xlsm"))
{
    var ws = p.Workbook.Worksheets["MySheet"];

    // Set some cell values here

    // Filtering, sorting, protection
    ws.Cells[7, 1, 10, 5].AutoFilter = true;
    ws.View.FreezePanes(7, 1);
    ws.ProtectedRanges.Add("FilteredCells", new ExcelAddress(7, 1, 10, 5));

    // Worksheet protection
    ws.Protection.AllowAutoFilter = true;
    ws.Protection.AllowDeleteColumns = false;
    ws.Protection.AllowDeleteRows = false;
    ws.Protection.AllowEditObject = false;
    ws.Protection.AllowEditScenarios = false;
    ws.Protection.AllowFormatCells = false;
    ws.Protection.AllowFormatColumns = false;
    ws.Protection.AllowFormatRows = false;
    ws.Protection.AllowInsertColumns = false;
    ws.Protection.AllowInsertHyperlinks = false;
    ws.Protection.AllowInsertRows = false;
    ws.Protection.AllowPivotTables = false;
    ws.Protection.AllowSelectLockedCells = false;
    ws.Protection.AllowSelectUnlockedCells = true;
    ws.Protection.AllowSort = true;
    ws.Protection.IsProtected = true;
    ws.Protection.SetPassword("hunter2");

    p.SaveAs(new FileInfo("output.xlsm"));
}

这段代码运行没有错误,但当我在Excel中打开文件或将其重新加载到EPPlus中时,发现已应用不同的保护选项:

AllowAutoFilter = false
AllowDeleteColumns = false
AllowDeleteRows = false
AllowEditObject = true
AllowEditScenarios = true
AllowFormatCells = false
AllowFormatColumns = false
AllowFormatRows = false
AllowInsertColumns = false
AllowInsertHyperlinks = false
AllowInsertRows = false
AllowPivotTables = false
AllowSelectLockedCells = true
AllowSelectUnlockedCells = true
AllowSort = false
IsProtected = true

这显然不是我之前设置的权限,那么我该如何确保它们被正确设置?其他所有内容都已经正确保存。

1个回答

7
这里是源代码: https://github.com/pruiz/EPPlus/blob/master/EPPlus/ExcelSheetProtection.cs 设置 IsProtected 属性会覆盖您的选择:
 public bool IsProtected
    {
        get
        {
            return GetXmlNodeBool(_isProtectedPath, false);
        }
        set
        {
            SetXmlNodeBool(_isProtectedPath, value, false);
            if (value)
            {
                AllowEditObject = true;
                AllowEditScenarios = true;
            }
            else
            {
                DeleteAllNode(_isProtectedPath); //delete the whole sheetprotection node
            }
        }
    }

把你的IsProtected = true调用移到代码的开头或者按照你的需要进行处理,因为你不小心覆盖了之前的选择。建议查看该链接中的属性,以确定哪些属性会覆盖你现有的选择。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接