【发布时间】:2013-12-23 22:00:09
【问题描述】:
有没有办法使用 EPPlus 使一列或一组单元格锁定或只读?我已经单独和一起尝试了下面的代码,但似乎都没有达到预期的效果。要么整个工作表被锁定(如果我包含IsProtected 语句),要么什么都没有。
ws.Protection.IsProtected = true;
ws.Column(10).Style.Locked = true;
编辑
这是来自我的控制器的整个代码块
FileInfo newFile = new FileInfo("C:\\Users\\" + User.Identity.Name + "\\Desktop" + @"\\ZipCodes.xlsx");
ExcelPackage pck = new ExcelPackage(newFile);
var ws = pck.Workbook.Worksheets.Add("Query_" + DateTime.Now.ToString());
//Headers
ws.Cells["A1"].Value = "ChannelCode";
ws.Cells["B1"].Value = "DrmTerrDesc";
ws.Cells["C1"].Value = "IndDistrnId";
ws.Cells["D1"].Value = "StateCode";
ws.Cells["E1"].Value = "ZipCode";
ws.Cells["F1"].Value = "EndDate";
ws.Cells["G1"].Value = "EffectiveDate";
ws.Cells["H1"].Value = "LastUpdateId";
ws.Cells["J1"].Value = "ErrorCodes";
ws.Cells["K1"].Value = "Status";
ws.Cells["I1"].Value = "Id";
//Content
int i = 2;
foreach (var zip in results)
{
ws.Cells["A" + i.ToString()].Value = zip.ChannelCode;
ws.Cells["B" + i.ToString()].Value = zip.DrmTerrDesc;
ws.Cells["C" + i.ToString()].Value = zip.IndDistrnId;
ws.Cells["D" + i.ToString()].Value = zip.StateCode;
ws.Cells["E" + i.ToString()].Value = zip.ZipCode;
ws.Cells["F" + i.ToString()].Value = zip.EndDate.ToShortDateString();
ws.Cells["G" + i.ToString()].Value = zip.EffectiveDate.ToShortDateString();
ws.Cells["H" + i.ToString()].Value = zip.LastUpdateId;
ws.Cells["J" + i.ToString()].Value = zip.ErrorCodes;
ws.Cells["K" + i.ToString()].Value = zip.Status;
ws.Cells["I" + i.ToString()].Value = zip.Id;
i++;
}
//ws.Protection.IsProtected = true;
ws.Column(10).Style.Locked = true;
return new ExcelResult
{
FileName = "ZipCodes.xlsx",
Package = pck
};
Excel结果
public class ExcelResult : ActionResult
{
public string FileName { get; set; }
public ExcelPackage Package { get; set; }
public override void ExecuteResult(ControllerContext context)
{
context.HttpContext.Response.Buffer = true;
context.HttpContext.Response.Clear();
context.HttpContext.Response.AddHeader("content-disposition", "attachment; filename=" + FileName);
context.HttpContext.Response.ContentType = "application/vnd.ms-excel";
context.HttpContext.Response.BinaryWrite(Package.GetAsByteArray());
}
}
二次编辑
我试图通过将IsProtected 值设置为true 来保护工作表,然后将除最后一列之外的每一列的Locked 属性设置为false。电子表格不仅不是只读模式,而且我可以编辑每一列中的数据。
我确实注意到了,但是我无法自行调整实际列的大小,所以也许这就是我正在做的事情。但是,我想锁定列中的每个单元格,因此无法输入新数据。
for (int a = 1; a < 10; a++)
{
ws.Column(a).Style.Locked = false;
}
ws.Protection.IsProtected = true;
【问题讨论】:
标签: c# .net asp.net-mvc-3 excel epplus