如何使用VB.Net在Excel中解锁列?

早上好

我有一个在VB.Net中的程序,从Datagridview导出到Excel文件,它看起来像这样。

在这里输入图像说明

我的目标是如何locking一些列? 基于上面的图像? locking除黄色的列以外的所有列? 我的意思是除黄色以外的所有列都是不可编辑的。

这是我在导出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的帮助

将单元格的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