带有 Epplus 的受保护工作表 - 需要允许过滤和排序。不允许排序

时间:2021-01-19 23:10:00

标签: c# .net excel spreadsheet epplus

以下方法的目的是在使用 Epplus 将数据写入工作表后对工作表进行样式设置和保护。样式是正确的,并且适当的单元格(在特定行中)受到保护。它旨在允许排序和过滤,尽管“标题”行单元格受到保护。

在生成的电子表格中,Excel 允许执行过滤。但是,排序遇到错误消息。如何解决这个问题?

public void FormatSpreadsheet(ExcelWorksheet worksheet)
{
    ExcelRange range;

    // styling header cells...

    range.AutoFilter = true;

    // protect headers and allow sorting and filtering, amongst other things
    worksheet.Protection.IsProtected = true;
    worksheet.Protection.AllowAutoFilter = true;
    worksheet.Protection.AllowDeleteColumns = false;
    worksheet.Protection.AllowDeleteRows = true;
    worksheet.Protection.AllowEditObject = true;
    worksheet.Protection.AllowEditScenarios = true;
    worksheet.Protection.AllowFormatCells = true;
    worksheet.Protection.AllowFormatColumns = true;
    worksheet.Protection.AllowFormatRows = true;
    worksheet.Protection.AllowInsertColumns = false;
    worksheet.Protection.AllowInsertHyperlinks = false;
    worksheet.Protection.AllowInsertRows = true;
    worksheet.Protection.AllowPivotTables = false;
    worksheet.Protection.AllowSelectLockedCells = true;
    worksheet.Protection.AllowSelectUnlockedCells = true;
    worksheet.Protection.AllowSort = true;

    // set a random password so it's impossible for anybody to edit the protected cells...

    // autofit columns
    range = worksheet.Cells[1, 1, worksheet.Dimension.End.Row, lastHeaderCol];
    range.AutoFitColumns();
}

1 个答案:

答案 0 :(得分:1)

您需要实际激活自动过滤器,而不仅仅是允许它。要使用工作表的第一行作为标题进行过滤,上面的 range 对象将起作用,您只需要再设置一个属性:

range.AutoFilter = true;