【问题标题】:Setting Excel worksheet protection with EPPlus使用 EPPlus 设置 Excel 工作表保护
【发布时间】:2017-05-10 15:57:48
【问题描述】:

我正在尝试使用 EPPlus 为 XLSM 文件设置工作表权限,但似乎我只能设置默认保护级别,没有设置个人保护。作为记录,我正在尝试以编程方式完成this article 中的方法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

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

【问题讨论】:

    标签: c# excel epplus worksheet


    【解决方案1】:

    这里是来源:

    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 调用移动到代码的开头或您想要的句柄,但您不小心覆盖了之前的选择。我会查看该链接上的属性,看看哪些属性会覆盖您现有的选择。

    【讨论】:

      猜你喜欢
      • 2016-11-05
      • 1970-01-01
      • 1970-01-01
      • 2013-06-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-08
      相关资源
      最近更新 更多