前端之家收集整理的这篇文章主要介绍了
vb.net excel数据导入datagridview显示,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
'''<summary>
'''从excel把数据导入datagridveiw中,Sheet代表excel中的工作表名称
'''</summary>
'''<param name="Sheet">Sheet代表excel中的工作表名称</param>
'''<param name="datagridview">datagridview代表数据要导入的datagridview名称</param>
Private Sub importexceltodatagridview(ByVal Sheet,ByVal datagridview)
Dim fileDialog As OpenFileDialog = New OpenFileDialog()
Dim FileName As String
'fileDialog.Filter = "Microsoft Excel files (*.xls)|*.xls"
If fileDialog.ShowDialog = Windows.Forms.DialogResult.Cancel Then
Exit Sub
Else
Try
FileName = fileDialog.FileName
Dim dataAdapter As New OleDbDataAdapter
Dim MyConnection As New OleDbConnection
Dim objcmd As OleDbCommand
Dim dst As New DataSet
Dim dt As New DataTable
MyConnection = New OleDbConnection( _
"Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=" & FileName & ";" & _
"Extended Properties='Excel 12.0;HDR=Yes;IMEX=1;'")
' Select the data from Sheet1 of the workbook.
MyConnection.Open()
objcmd = New OleDbCommand("select * from [" & Sheet & "$]",MyConnection)
dataAdapter.SelectCommand = objcmd
dataAdapter.Fill(dst,"info")
dt = dst.Tables("info")
dataAdapter.Update(dst,"info")
MyConnection.Close()
datagridview.AutoGenerateColumns = True
datagridview.DataSource = dt
'MsgBox("ok")
Catch ex As Exception
MessageBox.Show(ex.Message,"读取出错")
End Try
End If
原文链接:https://www.f2er.com/vb/257710.html