简体   繁体   English

保护 Excel - C# Epplus 中的某些单元格

[英]Protecting certain cells in Excel - C# Epplus

I have a program exporting a spreadsheet, containing headers and some data.我有一个导出电子表格的程序,其中包含标题和一些数据。 I need to protect the headers, but leave the data cells editable.我需要保护标题,但让数据单元格可编辑。

The problem is, upon setting the worksheet as protected, all the cells become read-only.问题是,将工作表设置为受保护后,所有单元格都变为只读。

So, the approach I am using is to check each of the cells below the header to see if they are not empty, and unlock them if so.因此,我使用的方法是检查 header 下方的每个单元格,看看它们是否不为空,如果是则解锁它们。

public void formatSpreadsheet(OfficeOpenXml.ExcelWorksheet ws)
{
    // autofit columns
    for (int i = 1; i <= ws.Dimension.End.Column; i++)
    {
        ws.Column(i).AutoFit();
    }

    // protect headers/metadata
    ws.Protection.IsProtected = true;
    int row = HEADER_ROW_OFFSET;
    int col = 1;


    while (ws.Cells[row,col].Value != null)
    {

        while (ws.Cells[row,col].Value != null)
        {
            ws.Cells[row, col].Style.Locked = false;
            col++;
        }
        row++;
    }

}

Testing for null values like so:测试 null 值,如下所示:

if (ws.Cells[row,col].Value != null)  ws.Cells[row,col].Style.Locked = false;

doesn't work.不起作用。

I have also tried ToString() on the cell values, and it doesn't help.我也在单元格值上尝试了 ToString() ,但它没有帮助。

Any ideas?有任何想法吗?

Your problem isn't the locking, but your loop that goes through the cells:您的问题不是锁定,而是您通过单元格的循环:

while (ws.Cells[row,col].Value != null)

As soon as it hits an empty cell, it will immediately exit the block, and nothing else will be performed.一旦它碰到一个空单元格,它将立即退出该块,并且不会执行任何其他操作。

The following should work fine:以下应该可以正常工作:

// Lock the worksheet. You can do this here, or in the end. Doesn't really matter.
ws.Protection.IsProtected = true;

// Assuming `HEADER_ROW_OFFSET` is the first row that's not a header,
// we first define a "data" range as starting from the first column of that row, 
// to the very last used row & column.
var dataCells = ws.Cells[HEADER_ROW_OFFSET, 1, ws.Dimension.End.Row, ws.Dimension.End.Column];

// Now go through each cell in that range,
foreach (var cel in dataCells)
{
    // and unlock when it has content.
    if (cel.Value != null) cel.Style.Locked = false;
}

Locking the entire spreadsheet, automatically permanently locks the cells.锁定整个电子表格会自动永久锁定单元格。 If you want to only have certain cells locked, go trough the spreadsheet and lock them (leaving the spreadsheet itself unlocked)如果您只想锁定某些单元格,go 通过电子表格并锁定它们(让电子表格本身解锁)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM