ชุมชนคนรักภาษาเบสิค - Visual Basic Community

 ลืมรหัสผ่าน
 ลงทะเบียน
ค้นหา
ดู: 5060|ตอบกลับ: 3

[VB.NET] การนำไฟล์ MS Excel มาทำงานเป็นเหมือนฐานข้อมูล (DataBase Excel)

[คัดลอกลิงก์]

308

กระทู้

498

โพสต์

5973

เครดิต

ผู้ดูแลระบบ

ทองก้อน ทับทิมกรอบ

Rank: 9Rank: 9Rank: 9

เครดิต
5973




ถามว่าให้ Excel ทำงานเป็นเหมือนฐานข้อมูล หรือ DataBase ได้หรือไม่ แอดมินตอบได้เลยว่าทำได้ครับ แต่ไม่ค่อยเหมาะสมเท่าใดนัก เพราะใช้งานผิดวัตถุประสงค์น่ะครับ แต่ในบางกรณีบางคนอาจจะมีชุดข้อมูลจาก Excel อยู่แล้ว ก็ไม่อยากจะย้ายข้อมูลไปเก็บที่ Access หรืออื่นๆ โค้ดชุดนี้แอดมินจะสาธิตและนำทางให้แบบเบื้องต้น คือ
การเพิ่มข้อมูลเข้าไปใน Excel โดยใช้ ADO.NET แทน Excel Object ครับผม ...
มาดูโค้ดกันเถอะ ...
  1. ' / --------------------------------------------------------------------------------
  2. ' / Developer : Mr.Surapon Yodsanga (Thongkorn Tubtimkrob)
  3. ' / eMail : thongkorn@hotmail.com
  4. ' / URL: http://www.g2gnet.com (Khon Kaen - Thailand)
  5. ' / Facebook: https://www.facebook.com/g2gnet (For Thailand)
  6. ' / Facebook: https://www.facebook.com/commonindy (Worldwide)
  7. ' / MORE: http://www.g2gnet.com/webboard
  8. ' /
  9. ' / Microsoft Excel is able to perform back ends provide.
  10. ' / Microsoft Visual Basic .NET (2010)
  11. ' /
  12. ' / This is open source code under @Copyleft by Thongkorn Tubtimkrob.
  13. ' / You can modify and/or distribute without to inform the developer.
  14. ' / --------------------------------------------------------------------------------
  15. Imports System.Data.OleDb

  16. Public Class frmExcelDBBackEnd
  17.     '// Path and File name of Excel
  18.     Dim strFilename As String

  19.     ' / --------------------------------------------------------------------------------
  20.     ' / Get my project path
  21.     ' / AppPath = C:\My Project\bin\debug
  22.     ' / Replace "\bin\debug" with ""
  23.     ' / Return : C:\My Project\
  24.     Function MyPath(ByVal AppPath As String) As String
  25.         '/ MessageBox.Show(AppPath);
  26.         AppPath = AppPath.ToLower()
  27.         '/ Return Value
  28.         MyPath = AppPath.Replace("\bin\debug", "").Replace("\bin\release", "")
  29.         '// If not found folder then put the \ (BackSlash) at the end.
  30.         If Microsoft.VisualBasic.Right(MyPath, 1) <> "" Then MyPath = MyPath & ""
  31.     End Function

  32.     Private Function CreateConnString(ByVal strFilename As String) As String
  33.         Return "Provider=Microsoft.Jet.OLEDB.4.0; Data Source = " + strFilename + "; Extended Properties=""Excel 8.0;HDR=YES"";"
  34.     End Function

  35.     Private Sub frmExcelDBBackEnd_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
  36.         Call ClearScreen()
  37.         '// Create Excel File
  38.         strFilename = MyPath(Application.StartupPath) + "Book1.xls"
  39.         '// Check file exists.
  40.         If Not (My.Computer.FileSystem.FileExists(strFilename)) Then
  41.             '// Not found
  42.             Dim Conn As New OleDbConnection
  43.             Dim Comm As New OleDbCommand

  44.             Conn.ConnectionString = CreateConnString(strFilename)
  45.             Comm.Connection = Conn
  46.             '// Create a new sheet consisting of three columns.
  47.             Comm.CommandText = "Create Table MySheet (MemberID Char(255), Firstname Char(255), Lastname Char(255), MemberShip Char(255))"
  48.             Try
  49.                 Conn.Open()
  50.                 Comm.ExecuteNonQuery()
  51.                 MsgBox("Created MS Excel successful.")
  52.                 Conn.Close()
  53.             Catch ex As Exception
  54.                 MsgBox("Error: " & ex.Message)
  55.                 Conn.Close()
  56.             End Try
  57.         Else
  58.             MessageBox.Show("The Excel file exists.", "Report status", MessageBoxButtons.OK, MessageBoxIcon.Information)
  59.         End If
  60.     End Sub

  61.     Private Sub btnInsert_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnInsert.Click
  62.         If Trim(txtMemberID.Text.Length) = 0 Or Trim(txtMemberID.Text) = "" Then
  63.             MessageBox.Show("Please enter Member ID.", "Report status", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
  64.             txtMemberID.Focus()
  65.             Return
  66.         End If

  67.         Dim Conn As New OleDbConnection
  68.         Dim Comm As New OleDbCommand
  69.         Conn.ConnectionString = CreateConnString(MyPath(Application.StartupPath) + "Book1.xls")
  70.         Comm.Connection = Conn
  71.         Dim strSQL As String = _
  72.                 " INSERT INTO [MySheet$] (" & _
  73.                 " MemberID, Firstname, Lastname, MemberShip) " & _
  74.                 " VALUES (" & _
  75.                 "'" & txtMemberID.Text & "'," & _
  76.                 "'" & txtFirstname.Text & "'," & _
  77.                 "'" & txtLastname.Text & "'," & _
  78.                 "'" & cmbMembership.Text & "'" & _
  79.                 ")"
  80.         Comm.CommandText = strSQL
  81.         Try
  82.             Conn.Open()
  83.             Comm.ExecuteNonQuery()
  84.             MsgBox("Inserted new record successful.")
  85.             Conn.Close()
  86.             '// Clear screen
  87.             Call ClearScreen()

  88.         Catch ex As Exception
  89.             MsgBox("Error: " & ex.Message)
  90.             Conn.Close()
  91.         End Try
  92.     End Sub

  93.     Private Sub ClearScreen()
  94.         '// Clear
  95.         txtMemberID.Clear()
  96.         txtFirstname.Clear()
  97.         txtLastname.Clear()
  98.         txtMemberID.Focus()
  99.         '//
  100.         With cmbMembership
  101.             .Items.Clear()
  102.             .Items.Add("Normal")
  103.             .Items.Add("Level I")
  104.             .Items.Add("Level II")
  105.             .Items.Add("Level III")
  106.             .Items.Add("VIP")
  107.             .SelectedIndex = 0
  108.         End With
  109.     End Sub

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

  113.     Private Sub frmExcelDBBackEnd_FormClosed(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
  114.         Me.Dispose()
  115.         Application.Exit()
  116.     End Sub

  117. End Class
คัดลอกไปที่คลิปบอร์ด



ดาวน์โหลดโค้ดต้นฉบับตัวเต็ม VB.NET (2010) ได้ที่นี่ ...



ขออภัย! โพสต์นี้มีไฟล์แนบหรือรูปภาพที่ไม่ได้รับอนุญาตให้คุณเข้าถึง

คุณจำเป็นต้อง ลงชื่อเข้าใช้ เพื่อดาวน์โหลดหรือดูไฟล์แนบนี้ คุณยังไม่มีบัญชีใช่ไหม? ลงทะเบียน

x
สิ่งที่ดีกว่าการให้ คือการให้แบบไม่มีที่สิ้นสุด

3

กระทู้

17

โพสต์

265

เครดิต

Full Member

Rank: 3Rank: 3

เครดิต
265
โพสต์ 2019-1-21 16:05:44 | ดูโพสต์ทั้งหมด

HelpMe

แก้ไขครั้งสุดท้ายโดย anuyut1995 เมื่อ 2019-1-21 16:07

Eroror ตรงปุ่มบันทึกนะครับ แต่ ฟอร์ม Load ไม่error

ขออภัย! โพสต์นี้มีไฟล์แนบหรือรูปภาพที่ไม่ได้รับอนุญาตให้คุณเข้าถึง

คุณจำเป็นต้อง ลงชื่อเข้าใช้ เพื่อดาวน์โหลดหรือดูไฟล์แนบนี้ คุณยังไม่มีบัญชีใช่ไหม? ลงทะเบียน

x

1

กระทู้

7

โพสต์

93

เครดิต

Member

Rank: 2

เครดิต
93
โพสต์ 2021-3-6 18:34:34 | ดูโพสต์ทั้งหมด

อาจารย์ครับ มีวิธีการเปลี่ยนจาก Excel file เป็น csv file ใหมครับ

308

กระทู้

498

โพสต์

5973

เครดิต

ผู้ดูแลระบบ

ทองก้อน ทับทิมกรอบ

Rank: 9Rank: 9Rank: 9

เครดิต
5973
 เจ้าของ| โพสต์ 2021-3-7 19:00:34 | ดูโพสต์ทั้งหมด

ooddog ตอบกลับเมื่อ 2021-3-6 18:34
อาจารย์ครับ มีวิธีการเปลี่ยนจาก Excel file เป็น csv file ใหมครับ

ลองดูโค้ดตัวนี้ก่อนครับ แหล่งที่มา ... ปกติผมใช้ความสามารถของ Component เช่น DevExpress หรือของฟรี Syncfusion แทนครับ ง่ายกว่ากันเยอะ

''' <summary>
''' Create a csv file from the active worksheet. You can of course
''' change this by passing in a SheetName
''' </summary>
''' <param name="ExcelFileName">Excel File to work with</param>
''' <param name="CsvFileName">Output file name in csv format</param>
''' <remarks>
''' See also:
''' http://code.msdn.microsoft.com/Basics-of-using-Excel-4453945d
''' Has several examples to assist in modifying this code to accept a SheetName
''' and uses assertion to ensure a passed Sheet exists.
''' </remarks>
''' <example>Usage example:<code>
''' Create_ExcelFile_InCsvFormat(
'''     IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "YourFileName.xlsx"),
'''     IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "YourFileName.txt")
''' )
''' </code>
''' </example>
Public Sub Create_ExcelFile_InCsvFormat(ByVal ExcelFileName As String,
    ByVal CsvFileName As String)

    If IO.File.Exists(ExcelFileName) Then
        Dim xlApp As Excel.Application = Nothing
        Dim xlWorkBooks As Excel.Workbooks = Nothing
        Dim xlWorkBook As Excel.Workbook = Nothing
        Dim xlWorkSheet As Excel.Worksheet = Nothing

        xlApp = New Excel.Application
        xlApp.DisplayAlerts = False

        xlWorkBooks = xlApp.Workbooks
        xlWorkBook = xlWorkBooks.Open(ExcelFileName)

        xlWorkSheet = CType(xlWorkBook.ActiveSheet, Excel.Worksheet)

        xlWorkBook.SaveAs(CsvFileName, FileFormat:=Excel.XlFileFormat.xlCSVWindows)

        xlWorkBook.Close()

        xlApp.UserControl = True
        xlApp.Quit()

        If Not xlWorkSheet Is Nothing Then
            Marshal.FinalReleaseComObject(xlWorkSheet)
            xlWorkSheet = Nothing
        End If

        If Not xlWorkBook Is Nothing Then
            Marshal.FinalReleaseComObject(xlWorkBook)
            xlWorkBook = Nothing
        End If

        If Not xlWorkBooks Is Nothing Then
            Marshal.FinalReleaseComObject(xlWorkBooks)
            xlWorkBooks = Nothing
        End If

        If Not xlApp Is Nothing Then
            Marshal.FinalReleaseComObject(xlApp)
            xlApp = Nothing
        End If
    Else
        MessageBox.Show("Failed to located " & ExcelFileName)
    End If
End Sub
สิ่งที่ดีกว่าการให้ คือการให้แบบไม่มีที่สิ้นสุด

308

กระทู้

498

โพสต์

5973

เครดิต

ผู้ดูแลระบบ

ทองก้อน ทับทิมกรอบ

Rank: 9Rank: 9Rank: 9

เครดิต
5973
 เจ้าของ| โพสต์ 2021-3-7 19:05:00 | ดูโพสต์ทั้งหมด

อันนี้ของฟรีจาก Syncfusion ครับ How to export Excel data to CSV file? ...
สิ่งที่ดีกว่าการให้ คือการให้แบบไม่มีที่สิ้นสุด
ขออภัย! คุณไม่ได้รับสิทธิ์ในการดำเนินการในส่วนนี้ กรุณาเลือกอย่างใดอย่างหนึ่ง ลงชื่อเข้าใช้ | ลงทะเบียน

รายละเอียดเครดิต

ข้อความล้วน|อุปกรณ์พกพา|ประวัติการแบน|G2GNet.com  

GMT+7, 2024-3-29 20:29 , Processed in 0.305138 second(s), 4 queries , File On.

Powered by Discuz! X3.4, Rev.62

Copyright © 2001-2020 Tencent Cloud.

ตอบกระทู้ ขึ้นไปด้านบน ไปที่หน้ารายการกระทู้