使用 ClosedXml 锁定 Excel 工作表中的列

问题描述 投票:0回答:1

我正在掌握使用 ClosedXml 并尝试让它锁定整个列。我是这样设置的:

void addingDataTable()
{
    using (XLWorkbook workbook = new XLWorkbook())
    {
        DataTable dt = GetTable("Information");

        var worksheet = workbook.Worksheets.Add(dt);

        ProtectColumn(worksheet, "Drug");
        workbook.SaveAs("C:\\Training\\excel sheet examples\\AddingDataTableAsWorksheet.xlsx");
    }
}

DataTable GetTable(string tableName)
{
        DataTable table = new DataTable();
        table.TableName = tableName;
        table.Columns.Add("Dosage", typeof(int));
        table.Columns.Add("Drug", typeof(string));
        table.Columns.Add("Patient", typeof(string));
        table.Columns.Add("Date", typeof(DateTime));
    
        table.Rows.Add(25, "Indocin", "David", DateTime.Now);
        table.Rows.Add(50, "Enebrel", "Sam", DateTime.Now);
        table.Rows.Add(10, "Hydralazine", "Christoff", DateTime.Now);
        table.Rows.Add(21, "Combivent", "Janet", DateTime.Now);
        table.Rows.Add(100, "Dilantin", "Melanie", DateTime.Now);
        return table;
}

static void ProtectColumn(IXLWorksheet worksheet, string columnName)
{
    // Protect the entire column
    worksheet.Column("Drug").Style.Protection.SetLocked(true);
}

但是,当我运行该应用程序时,我收到此错误:

System.ArgumentOutOfRangeException:'指定的参数超出了有效值的范围。 Arg_ParamName_Name'

当到达

ProtectColumn
方法时。我不知道我哪里出错了?

c# closedxml
1个回答
0
投票

您收到的错误表明通过名称“Drug”识别列时存在问题。发生这种情况的原因可能是 ClosedXML 无法正确识别列名称,或者可能是因为工作表保护尚未正确配置。

在 ClosedXML 中,要保护列中的单元格,实际上需要做两件事:

  1. 将要保护的列中单元格的
    Locked
    属性设置为
    true
  2. 启用工作表保护。

这是您的

ProtectColumn
方法的修订版本,应该同时执行这两个操作:

static void ProtectColumn(IXLWorksheet worksheet, string columnName)
{
    // Assuming you want to lock the entire column, which will likely be from row 1 onwards.
    // Find the index of the column with the specified name.
    int columnIndex = worksheet.Column(columnName).ColumnNumber();
    
    // Lock the cells in this column.
    worksheet.Column(columnIndex).Style.Protection.Locked = true;

    // Enable sheet protection.
    worksheet.Protect() // You can also set a password here if necessary.
        .SetFormatCells(false)
        .SetFormatColumns(false)
        .SetFormatRows(false)
        .SetInsertColumns(false)
        .SetInsertRows(false)
        .SetInsertHyperlinks(false)
        .SetDeleteColumns(false)
        .SetDeleteRows(false)
        .SetSort(false)
        .SetAutoFilter(false)
        .SetPivotTables(false);
}

这样,当工作表受到保护时,指定的整个列应该被锁定。一旦启用保护,锁定的单元格将无法修改,直到保护被禁用。

另一个重要注意事项是,当您通过

.Style.Protection.Locked = true;
应用列保护时,它将应用于列中的所有单元格。但这种保护只有在启用工作表保护后才会强制执行,正如您在
worksheet.Protect()
调用中看到的那样。

请在您的代码中使用此修改后的方法,并检查异常是否已解决以及列保护是否按预期工作。确保电子表格中存在列名称,否则将抛出

ArgumentException
,指出“指定的列名称无效,因为它在当前上下文中不存在”。当按名称引用时,ClosedXML 中的列名称区分大小写。

© www.soinside.com 2019 - 2024. All rights reserved.