我有一个导出电子表格的程序,其中包含标题和一些数据。我需要保护标题,但保持数据单元可编辑。
问题在于,将工作表设置为受保护时,所有单元格都变为只读。
因此,我使用的方法是检查标题下的每个单元格,以查看它们是否不为空,如果为空,则将其解锁。
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++;
}
}
测试空值,如下所示:
if (ws.Cells[row,col].Value != null) ws.Cells[row,col].Style.Locked = false;
不起作用。
我也尝试对单元格值使用ToString(),但这没有帮助。
有任何想法吗?
最佳答案
您的问题不是锁定,而是遍历单元格的循环:
while (ws.Cells[row,col].Value != null)
一旦碰到一个空单元格,它将立即退出该块,并且将不执行其他任何操作。
以下应该可以正常工作:
// 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;
}