从.Net Excel行locking
我从代码生成Excel电子表格。 我正在尝试使用.net代码自定义单元格,我想locking标题行,以便不允许将文本input到这些单元格中。
我尝试以下两种方式,但没有成功
-
worksheet.Range(“A1”,“A1”)。EntireRow.Locked = True
-
worksheet.Unprotect()
worksheet.Range(“A1”,“A100”)。Locked = True
worksheet.Protect()
这是我在这里失踪的东西吗?
– -码 – –
Public Sub CreatNewExcelWithAppliedRules(ByVal noOfWSheets As List(Of String))
Dim misValue As Object = System.Reflection.Missing.Value Dim App As New Application Dim workbook As Workbook = App.Workbooks.Add() Dim worksheet As Worksheet = workbook.Worksheets(1) Dim sFile As String = "sample-excel" ---READ HEADERS FROM XML Dim xmlFile = "E:\ExcelPOC\ExcelValidation\App_Data\Headers.xml" Dim fsReadXml As New System.IO.FileStream(xmlFile, System.IO.FileMode.Open) dsHeaders.ReadXml(fsReadXml) dtHeader = dsHeaders.Tables("Column") ---ADD HEADERS LIST TO EXCEL FillColumnHeader(worksheet, dtHeader, culture) worksheet.Unprotect() ---ADD VALIDATION RULES For Each worksheet In workbook.Worksheets ListValidExcelRule(worksheet) DateValidExcelRule(worksheet) TextLengthValidExcelRule(worksheet) DecimalValidExcelRule(worksheet) Next worksheet.Range("1:1").Locked = True worksheet.Protect() ---SAVE THE EXCEL sFile = App.GetSaveAsFilename(InitialFilename:=sFile, FileFilter:="xls Files (*.xls), *.xls") If sFile <> "False" Then workbook.SaveAs(Filename:=sFile, _ FileFormat:=XlFileFormat.xlWorkbookNormal, _ Password:="", _ WriteResPassword:="", _ ReadOnlyRecommended:=False, _ CreateBackup:=False) Else App.DisplayAlerts = False End If workbook.Close(True, misValue, misValue) App.Quit() releaseObject(worksheet) releaseObject(workbook) releaseObject(App) End Sub
A1:A100是左栏。 A1:IV1是第一排。 你的两个尝试都很接近。
尝试:
worksheet.Cells.Locked = False worksheet.Range("1:1").Locked = True worksheet.Protect
在新的Excel工作表中,默认情况下所有单元格都被locking。 除非您先解锁整个工作表,否则最好select要解锁的单元格而不是要locking的单元格。