如何使用C#.net创build只读Excel表单
我正在使用ExcelWorksheet创build一个dynamic的Excel工作表。 我需要创build一个不可编辑的Excel。 ws.Cells [“A1:Q12”]。Style.Locked = true 不起作用 。
这是我的代码:
Default.aspx.cs
protected void Page_Load(object sender, EventArgs e) { string filePath = Server.MapPath("~/Download/Sample.xlsx"); using (ExcelPackage pck = new ExcelPackage()) { FileInfo summaryFilePath = new FileInfo(filePath); ExcelWorksheet ws= pck.Workbook.Worksheets.Add("Sample Page"); CreateForamters(ws); } } private void CreateForamters(ExcelWorksheet ws) { ws.Cells["B8:L8"].Value = "SamplePage"; ws.Cells["B10:L10"].Value = DateTime.Now.ToString("MMM-yy"); ws.Cells["B11:L11"].Value = "test data........-"; ws.Cells["B8:L11"].Style.Fill.PatternType = ExcelFillStyle.Solid; ws.Cells["B8:L11"].Style.Font.Bold = true; ws.Cells["B8:L11"].Style.Font.Name = "Arial"; ws.Cells["B8:L11"].Style.Font.Size = 16; ws.Cells["B8:L11"].Style.Font.Color.SetColor(Color.Blue); ws.Cells["B8:L11"].Style.Fill.BackgroundColor.SetColor(Color.White); ws.Cells["B8:L11"].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center; ws.Cells["B8:L8"].Merge = true; ws.Cells["B9:L9"].Merge = true; ws.Cells["B10:L10"].Merge = true; ws.Cells["B11:L11"].Merge = true; ws.Cells["A1:Q12"].Style.Locked = true; }
提前谢谢大家的回复。
我正在使用ExcelWorksheet创build一个dynamic的Excel工作表。 我需要创build一个不可编辑的Excel。 ws.Cells [“A1:Q12”]。Style.Locked = true不起作用。
要创build不可编辑的单元格,您必须使用
ws.get_Range("A1", "Q12").Locked = true;
然后你需要保护工作表。 没有保护工作表, .Locked
命令没有任何意义。
这里是一个基本的例子( 在VS2010 + OFFICE2010中进行了testing和testing )
object misValue = System.Reflection.Missing.Value; ws.get_Range("A1", "Q12").Locked = true; string Password = "Sid"; ws.Protect(Password, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue);
注 :默认情况下,Excel中的所有单元格都被locking。 如果你不想保护工作表中其余的单元格,那么记得将它们的.Locked
属性设置为False
。
ws.Cells.Locked = false;
然后使用上面的代码。
如果要将Excel WorkBook另存为ReadOnly
另存为如下所示:
object misValue = System.Reflection.Missing.Value; ExcelWorkBook.ActiveWorkbook.SaveAs(save_path, Excel.XlFileFormat.xlWorkbookNormal, misValue , misValue , True, True,XlSaveAsAccessMode.xlShared, false, false, misValue, misValue , misValue );