Page 1 of 1

การเปิดไฟล์ Excel ใน VB.net

Posted: Mon Jul 04, 2022 12:34 am
by colinz
รบกวนสอบถามเกี่ยวกับการ Import Excel to DataGridview จากโค๊ดที่ผมเขียนไว้ หลังจากทดลองรันดูแล้ว ไม่สามารถใช้งานได้ รันแล้วหน้าต่างก็ปิดตัวกลับมาหน้าที่เขียนโค๊ดเหมือนเดิม เลยไม่แน่ใจว่าผมทำผิดตรงส่วนไหนหรือครับ

Code: Select all

Option Explicit On
Option Strict On

Imports Microsoft.Office.Interop.Excel
Imports System.Data.SqlClient
Imports System.Data.OleDb
Imports System.IO


Public Class Form1


    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

        Dim _dlgOpenFile As OpenFileDialog = New OpenFileDialog()
        Dim _oleConnect As OleDb.OleDbConnection
        Dim _oleCommand As OleDb.OleDbCommand
        Dim _oleAdapter As OleDb.OleDbDataAdapter
        Dim _dataSet As DataSet
        Dim _strConn As String

        With _dlgOpenFile
            .Title = "FIle Selection"
            .Filter = "All Files (*.*)|*.*|Excel files (*.xlsx)|*.xlsx|CSV Files (*.csv)|*.csv|XLS Files (*.xls)|*xls"
            .FilterIndex = 1
            .RestoreDirectory = True
        End With

        If _dlgOpenFile.ShowDialog() = DialogResult.OK Then
            'TextBox1.Text = dlgOpenFile.FileName

            _strConn =
                " Provider = Microsoft.ACE.OLEDB.12.0;" &
                " Data Source = " & _dlgOpenFile.FileName & ";" &
                " Extended Properties = Excel 12.0 XML;" &
                " HDR = YES"

            Try
                _oleConnect = New OleDb.OleDbConnection
                _oleCommand = New OleDb.OleDbCommand
                _oleConnect.ConnectionString = _strConn
                _oleCommand.CommandText = "Select * FROM [Sheet1]"
                _oleCommand.Connection = _oleConnect

                _oleAdapter = New OleDb.OleDbDataAdapter(_oleCommand)
                _dataSet = New DataSet
                _oleConnect.Open()
                _oleAdapter.Fill(_dataSet, "Sheet1")
                DataGridView1.DataSource = _dataSet.Tables("Sheet1")

            Catch ex As Exception
                MessageBox.Show(ex.Message)
            Finally
                _oleConnect = Nothing
                _oleCommand = Nothing
                _oleAdapter = Nothing
                _dataSet = Nothing
            End Try

        End If


    End Sub

End Class

Re: การเปิดไฟล์ Excel ใน VB.net

Posted: Mon Jul 04, 2022 1:33 pm
by snasui
:D ลองดูจาก Link นี้ครับ http://vb.net-informations.com/datagrid ... import.htm

อีกที่



จากที่เขียนมาควรจะ Debug แล้วดูว่า Code กระโดดออกไปที่ Catch ที่บรรทัดไหน จะได้ติดตามหาความผิดพลาดได้โดยเร็วครับ