读取Excel文件,加载数据到DataGridView

来源:互联网 发布:mac词典词库下载 编辑:程序博客网 时间:2024/05/17 23:35
 今天看到个好帖子,感觉很有用,很新鲜,贴出来备忘。代码未经测试,领会精神。
Public Class Form1
    
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        
Dim tb As DataTable = Nothing

        
Using dlg As New OpenFileDialog
            
With dlg
                .Filter 
= "*.xls|*.xls"
                .Multiselect 
= False

                
If .ShowDialog = Windows.Forms.DialogResult.OK Then
                    
Dim db As New LzmTW.Data.ExcelDatabase(.FileName)

                    
Dim tables As DataTable = db.GetConnectionSchema("Tables")

                    
'只取第一个
                    Dim firstSheet As String = tables.Rows(0)("TABLE_NAME").ToString

                    tb 
= db.GetDataTable("[" & firstSheet & "]")
                
End If

            
End With
        
End Using

        
If Not tb Is Nothing Then
            
Me.DataGridView1.DataSource = tb
        
End If
    
End Sub

End Class