【问题标题】:Excel-Protection from one sheet is set in another一张表的 Excel 保护设置在另一张表中
【发布时间】:2015-02-16 00:37:08
【问题描述】:

我使用 openXML 动态创建了一个 excel 文件。在这张纸里面有多张纸。在每个工作表内都可以有写保护的行。

我使用 excel 文件作为模板。在此模板中,有允许编辑的“正常”行和不允许编辑的行。我抓取该行并将其复制到我不希望用户能够编辑内容的地方:

private Row CloneRow(Row sourceRow, uint index, bool? hidden = null)
{
    var targetRow = (Row) sourceRow.CloneNode(true);
    if (hidden.HasValue)
    {
        targetRow.Hidden = hidden;
    }

    foreach (Cell cell in targetRow.Elements<Cell>())
    {
        // Update the references for reserved cells.
        string cellReference = cell.CellReference.Value;
        cell.CellReference = new StringValue(cellReference.Replace(targetRow.RowIndex.Value.ToString(), index.ToString()));
        cell.CellFormula = null;
    }
    // Update the row index.
    targetRow.RowIndex = new UInt32Value(index);

    return targetRow;
}

从模板中读取参数sourceRow:

List<Row> rows = sheet.ChildElements.OfType<Row>().ToList();
rowChangeAllowed=rows.FirstOrDefault(rw=>rw.RowIndex==3);
rowNotChangeAllowed=rows.FirstOrDefault(rw=>rw.RowIndex==4);

一切都按预期进行。但是当我在 Excel 中打开文件时,应在任何工作表上保护的行在所有工作表上都受到保护。

示例: 表 1:应保护第 4+5 行 第 2 页:第 7 行应受到保护。

现在在工作表 1 上,第 4,5 和 7 行受到保护

当我切换到第二张表时,突然一切都按需要运行了:在表 1 上,第 4+5 行仍然受到保护,但第 7 行没有。

因为该行为仅在打开文件后直接错误,但在我在工作表之间切换时是正确的:创建后是否需要调用其他命令来“刷新”文件?

其他问题: 当我更改工作表 1 中的单元格时,它也会在工作表 2 中自动更改(再次:直到我手动交换工作表一次)

【问题讨论】:

    标签: c# excel openxml


    【解决方案1】:

    问题在于工作表中有很多视图。下面的代码解决了这个问题:

    //There can only be one sheet that has focus
    SheetViews views = worksheetPart.Worksheet.GetFirstChild<SheetViews>();
    if (views != null)
    {
    views.Remove();
    worksheetPart.Worksheet.Save();
    }
    

    (从http://blogs.msdn.com/b/brian_jones/archive/2009/02/19/how-to-copy-a-worksheet-within-a-workbook.aspx得到它)

    【讨论】:

      猜你喜欢
      • 2019-04-21
      • 1970-01-01
      • 2019-11-15
      • 1970-01-01
      • 1970-01-01
      • 2018-12-24
      • 1970-01-01
      • 2014-08-09
      • 2014-09-29
      相关资源
      最近更新 更多