我使用带有excel的vb.net
我有一个按钮“从工作表中获取列的名称”和一个组合框
这是按钮的代码:
Private Sub Button7_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button7.Click
Dim Excols As New Dictionary(Of Integer, String)
Form2.xlWorkSheet = CType(Form2.xlWorkBook.Sheets(Form2.ComboBox1.Text), Excel.Worksheet)
Form2.xlWorkSheet.Activate()
With Form2.xlWorkSheet
Dim LastCol As Integer = Form2.xlWorkSheet.Cells(1,
Form2.xlWorkSheet.Columns.Count).End(XlDirection.xlToLeft).Column
For x As Integer = 2 To LastCol
Excols.Add(x, Form2.xlWorkSheet.Cells(1, x).value.ToString)
Next
ComboBox2.DataSource = New BindingSource(Excols, Nothing)
ComboBox2.ValueMember = "Key"
ComboBox2.DisplayMember = "Value"
AddHandler ComboBox2.SelectedIndexChanged, AddressOf
ComboBox2_SelectedIndexChanged
End With
End Sub
这是组合框的代码:
Private Sub ComboBox2_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)
Form2.xlWorkSheet = CType(Form2.xlWorkBook.Sheets(Form2.ComboBox1.Text), Excel.Worksheet)
Form2.xlWorkSheet.Activate()
Form2.xlApp.Visible = True
Dim key As String =
CStr(DirectCast(ComboBox2.SelectedItem, KeyValuePair(Of Integer, String)).Key)
Dim value As String =
DirectCast(ComboBox2.SelectedItem, KeyValuePair(Of Integer, String)).Value
Dim DoesSheetExists As Boolean = False
For Each xs In Form2.xlApp.Sheets
If xs.Name = value Then
DoesSheetExists = True
Next
If DoesSheetExists = True Then
MsgBox("Sheet already exists", CType(MessageBoxIcon.Error, MsgBoxStyle))
Else
With Form2.xlWorkSheet
Dim lastrow As Integer = Form2.xlWorkSheet.Cells.Rows.End(XlDirection.xlDown).Row
Dim colletter As String = ColumnIndexToColumnLetter(CInt(key))
exWS2 = DirectCast(Form2.xlWorkBook.Sheets.Add, Microsoft.Office.Interop.Excel.Worksheet)
exWS2.Name = value
Form2.xlWorkSheet.Range("A1:A" & lastrow.ToString).Copy(exWS2.Range("A1"))
Form2.xlWorkSheet.Range(colletter & "1:" & colletter & lastrow.ToString).Copy(exWS2.Range("B1"))
exWS2.Range("A1").Font.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Blue)
exWS2.Range("B1").Font.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Blue)
exWS2.Range("A1").Interior.ColorIndex = 8
exWS2.Range("B1").Interior.ColorIndex = 8
exWS2.Range("A2:A" & lastrow.ToString).Interior.ColorIndex = 20
exWS2.Range("A1:A" & lastrow.ToString).HorizontalAlignment = -4108
exWS2.Range("B1:B" & lastrow.ToString).HorizontalAlignment = -4108
exWS2.Range("A1").Font.Name = "Times New Roman"
exWS2.Range("B1").Font.Name = "Times New Roman"
exWS2.Range("B1").Font.FontStyle = "Gras"
exWS2.Range("A1").Font.FontStyle = "Gras"
End With
End If
End Sub
我想要的是每当我选择一个列时添加它,它将被添加到datagridview
这是我要添加到datagridview
的列 请帮助我