2011-08-18 47 views
1

我從代碼生成Excel電子表格。我正在嘗試使用.net代碼 來定製單元格,並且我想鎖定標題行,以便它不允許將文本輸入到這些單元格中。從.Net打印Excel行鎖定

我嘗試以下2種方式,但沒有成功

  1. worksheet.Range( 「A1」, 「A1」)。EntireRow.Locked =真

  2. worksheet.Unprotect()
    工作表.Range( 「A1」, 「A100」)。鎖定=真
    worksheet.Protect()

那是什麼我我在這裏失蹤?

--- --- CODE

公用Sub CreatNewExcelWithAppliedRules(BYVAL noOfWSheets方式列表(字符串))

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 
+0

您是否收到任何錯誤,或者它是否無法阻止對該行進行修改? – Patrick

+0

我沒有收到任何錯誤。它沒有應用鎖定並允許輸入文字 – ramesh

回答

2

A1:A100是左側列。 A1:IV1是第一排。你的兩次嘗試都很接近。

嘗試:

worksheet.Cells.Locked = False 
worksheet.Range("1:1").Locked = True 
worksheet.Protect 

在新的Excel工作表中所有單元格默認情況下鎖定。除非先解鎖整個工作表,否則最好選擇要解鎖的單元而不是要鎖定的單元。

+0

我嘗試了上述方法,但仍然允許在標題中輸入文本 – ramesh

+1

向我們展示更多代碼,例如定義「工作表」的位置。 –

+0

當我用工作表(1)替換'工作表'時,這適用於我。您可能需要根據生成Excel文件的方式更改索引。 – Patrick