更新时间:作者:小小条
Imports System.Data.OleDb
Public Class Form1

Private Sub Button导入_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button导入.Click
Try
Dim openFileDialog As New OpenFileDialog()
openFileDialog.Filter = "Excel Files|*.xls;*.xlsx"
openFileDialog.Title = "选择Excel文件"
If openFileDialog.ShowDialog() = DialogResult.OK Then
Dim filePath As String = openFileDialog.FileName
Dim connectionString As String = ""
If filePath.EndsWith(".xlsx") Then
connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & filePath & ";Extended Properties='Excel 12.0 xml;HDR=YES';"
Else
connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & filePath & ";Extended Properties='Excel 8.0;HDR=YES';"
End If
Using connection As New OleDbConnection(connectionString)
connection.Open()
Dim dtSchema As DataTable = connection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, Nothing)
Dim sheetName As String = dtSchema.Rows(0)("TABLE_NAME").ToString()
Dim query As String = "SELECT * FROM [" & sheetName & "]"
Dim adapter As New OleDbDataAdapter(query, connection)
Dim dt As New DataTable()
adapter.Fill(dt)
DataGridView1.DataSource = dt
MessageBox.Show("导入完成!")
End Using
End If
Catch ex As Exception
MessageBox.Show("导入失败:" & ex.Message)
End Try
End Sub
End Class
版权声明:本文转载于今日头条,版权归作者所有,如果侵权,请联系本站编辑删除