thongkorn โพสต์ 2023-11-15 14:56:27

[VB.NET] การ Import Excel เข้ามาใน ListView ด้วย Interop Service

โพสต์ก่อนหน้าเป็นการ Import Excel เข้ามาใน Listview Control ด้วยการใช้ ADO.NET คือการมอง Sheet เป็นเหมือนกับตารางข้อมูล (DataTable) คราวนี้จะใช้ Interop Service หรือการใช้งาน COM (Component Object Model) ก็เป็นเทคโนโลยีรุ่นเก่า ก่อนที่จะมาเป็น Dot Net ในทุกวันนี้แหละครับ ดังนั้นแล้วในเครื่องเราจะต้องทำการติดตั้ง MS Excel เอาไว้ก่อนด้วย เพราะต้อง Add Reference COM เข้ามาช่วย โดยจะทำการอ่านข้อมูลจาก Sheet เข้ามาทีละหลักและทีละแถว แล้วทำการเก็บชุดข้อมูลไว้ใน DataTable เหมือนกับการใช้ ADO.NET ทุกอย่าง แม้ว่าการอ่านข้อมูลเข้ามาจะทำได้ช้ากว่า ADO.NET แต่มันมีข้อดีคือสามารถเลือกเซลล์ หรือช่วงข้อมูล (Range) ที่เราต้องการได้ ...

http://www.g2gsoft.com/webboard/images/VBNet/worksheet2listview.png

http://www.g2gsoft.com/webboard/images/VBNet/worksheet2listviewref.png
เลือก Add References ... เลือก COM (Component Object Model) ทั้งนี้ก็ขึ้นอยู่กับเวอร์ชั่นของ Excel ที่ติดตั้งในเครื่องของแต่ละคน ...

มาดูโค้ดฉบับเต็มกันเถอะ ...
Imports Excel = Microsoft.Office.Interop.Excel

Public Class frmWorkSheet2ListView

    Dim DS As DataSet = New DataSet()

    ' / --------------------------------------------------------------------------------
    ' / เลือกไฟล์ Excel
    ' / --------------------------------------------------------------------------------
    Private Sub btnOpenExcel_Click(sender As System.Object, e As System.EventArgs) Handles btnOpenExcel.Click
      '/ ประกาศใช้งาน Open File Dialog ในแบบ Run Time
      Dim dlgOpenFile As OpenFileDialog = New OpenFileDialog()

      '// ตั้งค่าการใช้งาน Open File Dialog
      With dlgOpenFile
            .InitialDirectory = MyPath(System.Windows.Forms.Application.StartupPath)
            .Title = "เลือกไฟล์ MS Excel"
            .Filter = "XLSX Files (*.xlsx)|*.xlsx|XLS Files (*.xls)|*xls"
            .FilterIndex = 1
            .RestoreDirectory = True
      End With
      '// หากเลือกปุ่ม OK หลังจากการ Browse ...
      If dlgOpenFile.ShowDialog() = DialogResult.OK Then
            txtFileName.Text = dlgOpenFile.FileName
            '//
            cmbSheetName.Items.Clear()
            ListView1.Columns.Clear()
            '// Create a new Excel application
            Dim excelApp As New Excel.Application()
            '// Open the Excel workbook
            Dim workbook As Excel.Workbook = excelApp.Workbooks.Open(txtFileName.Text)
            Try
                '// เคลียร์ค่า Table/Query ของเดิมใน DataSet ก่อนใช้งานใหม่
                '// หรือหากให้เพิ่มตารางข้อมูล/คิวรี่ จากไฟล์อื่น ก็ตัดบรรทัดนี้ทิ้งออกไป
                DS = New DataSet()
                '// Loop through each worksheet in the workbook
                For Each worksheet As Excel.Worksheet In workbook.Sheets
                  '// Create a new DataTable for each worksheet.
                  Dim DT As New DataTable(worksheet.Name)
                  cmbSheetName.Items.Add(worksheet.Name)
                  '// Add columns to the DataTable.
                  For col As Integer = 1 To worksheet.UsedRange.Columns.Count
                        DT.Columns.Add(DirectCast(worksheet.Cells(1, col), Excel.Range).Value2.ToString())
                  Next
                  '// Loop through the rows and columns in the worksheet.
                  For row As Integer = 2 To worksheet.UsedRange.Rows.Count
                        Dim dataRow = DT.NewRow()
                        For col As Integer = 1 To worksheet.UsedRange.Columns.Count
                            dataRow(col - 1) = DirectCast(worksheet.Cells(row, col), Excel.Range).Value2
                        Next
                        DT.Rows.Add(dataRow)
                  Next
                  '// Add the DataTable to the DataSet.
                  DS.Tables.Add(DT)
                Next
            Catch ex As Exception
                '// Handle any exceptions that may occur during the process.
                MessageBox.Show("An error occurred: " & ex.Message)
            Finally
                '// Close and release resources
                workbook.Close()
                excelApp.Quit()
                System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook)
                System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApp)
            End Try
      End If
    End Sub

    ' / --------------------------------------------------------------------------------
    '// เลือก WorkSheet แล้วแสดงผลข้อมูลลงใน ListView
    ' / --------------------------------------------------------------------------------
    Private Sub cmbSheetName_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles cmbSheetName.SelectedIndexChanged
      With ListView1
            .Clear()
            .View = View.Details
            .GridLines = True
            .FullRowSelect = True
            .HideSelection = False
            .MultiSelect = False
      End With
      Try
            '/ Access the DataTable by its name.
            Dim DT As System.Data.DataTable = DS.Tables(cmbSheetName.Text)
            '/ Now you can work with the 'dataTable' as needed
            '/ For example, you can iterate through its rows and columns
            '// อ่านจำนวนหลักทั้งหมดเข้ามาก่อน
            For iCol = 0 To DT.Columns.Count - 1
                ListView1.Columns.Add(DT.Columns(iCol).ColumnName)
                '// ปรับระยะความกว้างใหม่
                ListView1.Columns(iCol).Width = ListView1.Width \ (DT.Columns.Count - 1)
            Next
            '// อ่านข้อมูลในแต่ละแถว
            For sRow = 0 To DT.Rows.Count - 1
                Dim LV As New ListViewItem
                Dim dRow As DataRow = DT.Rows(sRow)
                LV = ListView1.Items.Add(dRow.Item(0))'// --> Primary Node
                For iCol = 1 To DT.Columns.Count - 1
                  LV.SubItems.Add(dRow(iCol).ToString())
                Next
            Next
            ListView1.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize)
      Catch ex As Exception
            MessageBox.Show(ex.Message)
      End Try
    End Sub

    ' / --------------------------------------------------------------------------------
    ' / เหตุการณ์ Double Click Mouse บน ListView เพื่อแสดงผลข้อมูลในแถวรายการที่เลือก
    ' / --------------------------------------------------------------------------------
    Private Sub ListView1_DoubleClick(sender As Object, e As System.EventArgs) Handles ListView1.DoubleClick
      MessageBox.Show( _
            "Column 0: " & ListView1.SelectedItems(0).Text & vbCrLf & _
            "Column 1: " & ListView1.SelectedItems.Item(0).SubItems(1).Text & vbCrLf & _
            "Column 2: " & ListView1.SelectedItems.Item(0).SubItems(2).Text & vbCrLf & _
            "Column 3: " & ListView1.SelectedItems.Item(0).SubItems(3).Text)
    End Sub

    Private Sub txtFileName_KeyPress(sender As Object, e As System.Windows.Forms.KeyPressEventArgs) Handles txtFileName.KeyPress
      e.Handled = True    '// Can't keypress.
    End Sub

    Private Sub btnExit_Click(sender As System.Object, e As System.EventArgs) Handles btnExit.Click
      Me.Close()
    End Sub

    Private Sub frmWorkSheet2ListView_FormClosed(sender As Object, e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
      Me.Dispose()
      GC.SuppressFinalize(Me)
      Application.Exit()
    End Sub

#Region "FUNCTION"
    ' / --------------------------------------------------------------------------------
    ' / Get my project path
    ' / AppPath = C:\My Project\bin\debug
    ' / Replace "\bin\debug" with "\"
    ' / Return : C:\My Project\
    Public Function MyPath(ByVal AppPath As String) As String
      '/ MessageBox.Show(AppPath);
      MyPath = AppPath.ToLower.Replace("\bin\debug", "\").Replace("\bin\release", "\").Replace("\bin\x86\debug", "\").Replace("\bin\x86\release", "\")
      '// If not found folder then put the \ (BackSlash) or ASCII Code = 92 at the end.
      '/ Return Value
      If Microsoft.VisualBasic.Right(MyPath, 1) <> Chr(92) Then MyPath = MyPath & Chr(92)
    End Function

#End Region

End Class
ดาวน์โหลดโค้ดต้นฉบับ VB.NET (2010) ได้ที่นี่ ...
หน้า: [1]
ดูในรูปแบบกติ: [VB.NET] การ Import Excel เข้ามาใน ListView ด้วย Interop Service