早上好
我在VB.Net中有一个程序,它将Datagridview中的文件导出到Excel文件中 它看起来像这样。
我的目标是如何锁定某些列?基于上面的图片?锁定除了黄色的列以外的所有列?我的意思是除了黄色之外的所有列都是不可编辑的。
这是我导出excel的代码
Try
If DataGridView1.Rows.Count = 0 Then
MsgBox("Nothing to Export")
Else
Dim ExcelApp As Object, ExcelBook As Object
Dim ExcelSheet As Object
Dim i As Integer
Dim J As Integer
Dim rowIndex As Integer = 1
Dim total As Double = 0
Dim indexTotal As Integer
ExcelApp = CreateObject("Excel.Application")
ExcelBook = ExcelApp.WorkBooks.Add
ExcelSheet = ExcelBook.WorkSheets(1)
With ExcelSheet
rowIndex += 2
For Each column As DataGridViewColumn In DataGridView1.Columns
.cells(rowIndex, column.Index + 1) = column.HeaderText
Next
.Range(.Cells(rowIndex, 1), .Cells(rowIndex, DataGridView1.Columns.Count)).Font.Bold = True
rowIndex += 1
For i = 0 To Me.DataGridView1.RowCount - 1
.cells(rowIndex, 1) = Me.DataGridView1.Rows(i).Cells("ItemCode").Value
For J = 1 To DataGridView1.Columns.Count - 1
If IsNumeric(DataGridView1.Rows(i).Cells(J).Value) Then
.cells(rowIndex, J + 1).NumberFormat = "#,##0.00"
.cells(rowIndex, J + 1) = DataGridView1.Rows(i).Cells(J).Value
Else
.cells(rowIndex, J + 1) = DataGridView1.Rows(i).Cells(J).Value
End If
'You can test also by index for example : if J = indexofTotalColumn then
If DataGridView1.Columns(J).Name = "Total" Then
total += DataGridView1.Rows(i).Cells(J).Value
indexTotal = J
End If
Next
rowIndex += 1
.Columns("A:Z").EntireColumn.AutoFit()
.Columns("L").ColumnWidth = 0
.cells(5).Locked = False
Next
.Protect("fakepwd")
End With
ExcelApp.Visible = True
ExcelSheet = Nothing
ExcelBook = Nothing
ExcelApp = Nothing
End If
Catch
End Try
TYSM寻求帮助
答案 0 :(得分:1)
将单元格的Locked
属性设置为false,其中J + 1是所需的列号。
例如解锁第5列:
For J = 1 To DataGridView1.Columns.Count - 1
If J=5 then
.cells(rowIndex, J + 1).Locked=False
End if
If IsNumeric(DataGridView1.Rows(i).Cells(J).Value) Then
..........
在代码中,完成在工作表中填充数据后,保护工作表
Next
.Protect ("fakepwd")
End With