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

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

[VB.NET] การ Import JSON เข้าสู่ตารางกริดและ Export ข้อมูลไป MS Access

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

311

กระทู้

502

โพสต์

6060

เครดิต

ผู้ดูแลระบบ

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

Rank: 9Rank: 9Rank: 9

เครดิต
6060




Add References NewtonSoft.Json และ COM ที่จัดการไฟล์ฐานข้อมูล ...

เป็นโค้ดที่ต่อเนื่องจากครั้งที่แล้ว หลังจากที่โหลดข้อมูลรหัสไปรษณีย์มาจาก JSON นำมาใส่ลงใน DataGridView ต่อจากนั้นก็จะทำการ Export เข้าสู่ไฟล์ MS Access โดยการสร้างชื่อไฟล์ข้อมูล ตามด้วยการสร้างตารางและฟิลด์ข้อมูลตามลำดับ ด้วยการใช้โค้ด VB.NET ในแบบไดนามิค แต่เนื่องจากว่าจำนวนรายการข้อมูลมีอยู่เจ็ดพันกว่ารายการ ซึ่งในระดับ File Base จะต้องใช้การส่งออกไปแบบทีละรายการ ซึ่งแตกต่างไปจาก File Server ที่สามารถใช้การคัดลอกไปแบบชุดได้ด้วย BulkCopy ในกรณีนี้จะเกิดอาการหน้าจอค้าง เราจึงต้องใช้ BackGround Worker เข้ามาช่วย เพื่อโยนงานให้ไปทำงานอยู่เบื้องหลังแทน ...

มาดูโค้ดฉบับเต็มกันเถอะ ... ฟอร์มหลัก frmJsonPostCode2Access.vb ...
  1. ' / ------------------------------------------------------------------------------------------------
  2. '// Special Thank ... Original JSON data.
  3. '// https://gist.github.com/mennwebs/8ff8e27a01fd06ca2ac965a1c7317552
  4. ' / ------------------------------------------------------------------------------------------------

  5. ' / ------------------------------------------------------------------------------------------------
  6. '// Don't Forget Add References ... COM
  7. '// Microsoft Ext. 6.0 for DLL and Security.
  8. ' / ------------------------------------------------------------------------------------------------

  9. Imports Newtonsoft.Json
  10. Imports System.IO
  11. Imports System.Data.OleDb

  12. Public Class frmJsonPostCode2Access
  13.     Private JsonSource As New BindingSource()

  14.     Private Sub btnExport_Click(sender As System.Object, e As System.EventArgs) Handles btnExport.Click
  15.         If dgvData.RowCount = 0 Then Return
  16.         '// Create instance form and call to frmProcess for show ProgressBar working with BackgroundWorker.
  17.         Dim frmProcess As New frmProcess
  18.         frmProcess.AcceptFormMain(Me)
  19.         frmProcess.ShowDialog()
  20.     End Sub

  21.     Private Sub frmJsonPostCode_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
  22.         '// JSON data as a string
  23.         Dim json = File.ReadAllText(MyPath(Application.StartupPath) & "src\th-address.json")
  24.         '// Deserialize JSON into a List(Of LocationData)
  25.         Dim dataList As List(Of LocationData) = JsonConvert.DeserializeObject(Of List(Of LocationData))(json)
  26.         Dim DT As New DataTable()
  27.         '// Add Columns to DataTable.
  28.         With DT.Columns
  29.             .Add("zipCode", GetType(String))
  30.             .Add("subDistrictId", GetType(String))
  31.             .Add("subDistrictName", GetType(String))
  32.             .Add("districtId", GetType(String))
  33.             .Add("districtName", GetType(String))
  34.             .Add("provinceId", GetType(String))
  35.             .Add("provinceName", GetType(String))
  36.         End With
  37.         '// Loop for add row data to DataTable.
  38.         Try
  39.             For Each LocationData In dataList
  40.                 For Each subDistrict In LocationData.subDistrictList
  41.                     Dim row As DataRow = DT.NewRow()
  42.                     row("zipCode") = LocationData.zipCode
  43.                     row("subDistrictId") = subDistrict.subDistrictId
  44.                     row("subDistrictName") = subDistrict.subDistrictName
  45.                     '//
  46.                     Dim matchingDistrict As District = Nothing '// Assuming District is the type of the elements in districtList.
  47.                     Dim currentSubDistrict = subDistrict '// Declare a local variable.
  48.                     '// Lambda Expression.
  49.                     matchingDistrict = LocationData.districtList.FirstOrDefault(Function(d) d.districtId = currentSubDistrict.districtId)
  50.                     If matchingDistrict IsNot Nothing Then
  51.                         row("districtId") = matchingDistrict.districtId
  52.                         row("districtName") = matchingDistrict.districtName
  53.                     End If
  54.                     '//
  55.                     Dim matchingProvince As Province = Nothing
  56.                     matchingProvince = LocationData.provinceList.FirstOrDefault(Function(p) p.provinceId = currentSubDistrict.provinceId)
  57.                     If matchingProvince IsNot Nothing Then
  58.                         row("provinceId") = matchingProvince.provinceId
  59.                         row("provinceName") = matchingProvince.provinceName
  60.                     End If
  61.                     DT.Rows.Add(row)
  62.                 Next
  63.             Next
  64.         Catch ex As Exception
  65.             MessageBox.Show(ex.Message)
  66.         End Try
  67.         '// ReOrder DataTable.
  68.         DT.DefaultView.Sort = "provinceName ASC, zipCode ASC, subDistrictName ASC, districtName ASC"
  69.         DT = DT.DefaultView.ToTable
  70.         '// Set DataTable as the DataSource for BindingSource.
  71.         JsonSource.DataSource = DT
  72.         '// Set BindingSource as the DataSource for DataGridView.
  73.         dgvData.DataSource = JsonSource
  74.         '// Remove some columns.
  75.         With dgvData.Columns
  76.             .Remove("subDistrictId")
  77.             .Remove("districtId")
  78.             .Remove("provinceId")
  79.         End With
  80.         '//
  81.         With dgvData
  82.             .Columns("zipCode").HeaderText = "รหัสไปรษณีย์"
  83.             .Columns("subDistrictName").HeaderText = "ตำบล/แขวง"
  84.             .Columns("districtName").HeaderText = "อำเภอ/เขต"
  85.             .Columns("provinceName").HeaderText = "จังหวัด"
  86.         End With
  87.         Call SetupGridView()
  88.         Me.lblRecordCount.Text = "Total: " & Format(dgvData.RowCount, "#,##") & " Records."
  89.     End Sub

  90.     ' / --------------------------------------------------------------------------------
  91.     '// Filter data.
  92.     ' / --------------------------------------------------------------------------------
  93.     Private Sub txtFilterJson_TextChanged(sender As Object, e As System.EventArgs) Handles txtFilterJson.TextChanged
  94.         If rdoFilterAll.Checked Then
  95.             '// Filter for All.
  96.             JsonSource.Filter = _
  97.                 " provinceName LIKE " & "'%" & txtFilterJson.Text & "%'" & _
  98.                 " OR districtName LIKE " & "'%" & txtFilterJson.Text & "%'" & _
  99.                 " OR subDistrictName LIKE " & "'%" & txtFilterJson.Text & "%'" & _
  100.                 " OR zipCode LIKE " & "'%" & txtFilterJson.Text & "%'"
  101.             '// Filter ProvinceName.
  102.         ElseIf rdoProvinceName.Checked Then
  103.             JsonSource.Filter = "provinceName LIKE " & "'%" & txtFilterJson.Text & "%'"
  104.             '// Filter DistrictName.
  105.         ElseIf rdoDistrictName.Checked Then
  106.             JsonSource.Filter = "districtName LIKE " & "'%" & txtFilterJson.Text & "%'"
  107.             '// Filter SubDistrictName.
  108.         ElseIf rdoSubDistrictName.Checked Then
  109.             JsonSource.Filter = "subdistrictName LIKE " & "'%" & txtFilterJson.Text & "%'"
  110.             '// Filter ZipCode.
  111.         ElseIf rdoZipCode.Checked Then
  112.             JsonSource.Filter = "zipCode LIKE " & "'%" & txtFilterJson.Text & "%'"
  113.         End If
  114.         '//
  115.         Me.lblRecordCount.Text = "Total: " & Format(dgvData.RowCount, "#,##") & " Records."
  116.     End Sub

  117.     Private Sub rdoFilterAll_CheckedChanged(sender As System.Object, e As System.EventArgs) Handles rdoFilterAll.CheckedChanged
  118.         txtFilterJson.Focus()
  119.     End Sub

  120.     Private Sub rdoProvinceName_CheckedChanged(sender As System.Object, e As System.EventArgs) Handles rdoProvinceName.CheckedChanged
  121.         txtFilterJson.Focus()
  122.     End Sub

  123.     Private Sub rdoDistrictName_CheckedChanged(sender As Object, e As System.EventArgs) Handles rdoDistrictName.CheckedChanged
  124.         txtFilterJson.Focus()
  125.     End Sub

  126.     Private Sub rdoSubDistrictName_CheckedChanged(sender As Object, e As System.EventArgs) Handles rdoSubDistrictName.CheckedChanged
  127.         txtFilterJson.Focus()
  128.     End Sub

  129.     Private Sub rdoZipCode_CheckedChanged(sender As Object, e As System.EventArgs) Handles rdoZipCode.CheckedChanged
  130.         txtFilterJson.Focus()
  131.     End Sub

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

  135.     Private Sub frmJsonPostCode2Access_FormClosed(sender As Object, e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
  136.         Me.Dispose()
  137.         GC.SuppressFinalize(Me)
  138.         Application.Exit()
  139.     End Sub

  140. #Region "DATAGRIDVIEW"
  141.     '// Initialized DataGridView.
  142.     Private Sub SetupGridView()
  143.         With dgvData
  144.             .RowHeadersVisible = True
  145.             .AllowUserToAddRows = False
  146.             .AllowUserToDeleteRows = False
  147.             .AllowUserToResizeRows = False
  148.             .MultiSelect = False
  149.             .SelectionMode = DataGridViewSelectionMode.FullRowSelect
  150.             .ReadOnly = True
  151.             '// Data rows
  152.             .Font = New Font("Tahoma", 10)
  153.             .RowTemplate.MinimumHeight = 27
  154.             .RowTemplate.Height = 27
  155.             '// Autosize Column
  156.             .AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill
  157.             '// Header
  158.             With .ColumnHeadersDefaultCellStyle
  159.                 .BackColor = Color.RoyalBlue
  160.                 .ForeColor = Color.White
  161.                 .Font = New Font(dgvData.Font, FontStyle.Bold)
  162.             End With
  163.             .ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.DisableResizing
  164.             .ColumnHeadersHeight = 36
  165.             '/ Accept changes to the header's background color.
  166.             .EnableHeadersVisualStyles = False
  167.             '// Even-Odd Color of Rows.
  168.             .AlternatingRowsDefaultCellStyle.BackColor = Color.Beige
  169.             '// Even-Odd Color of Columns.
  170.             For iCol As Integer = 0 To dgvData.Columns.Count - 1
  171.                 '// If any integer Mod by 2 and gets the answer is 0 so even number, 1 is an odd number.
  172.                 If iCol Mod 2 = 1 Then
  173.                     dgvData.Columns(iCol).HeaderCell.Style.BackColor = Color.BlueViolet
  174.                 Else
  175.                     dgvData.Columns(iCol).HeaderCell.Style.BackColor = Color.SeaGreen
  176.                 End If
  177.             Next
  178.         End With
  179.     End Sub
  180. #End Region

  181. End Class

  182. '// Define data model classes.
  183. Public Class SubDistrict
  184.     Public Property subDistrictId As String
  185.     Public Property districtId As String
  186.     Public Property provinceId As String
  187.     Public Property subDistrictName As String
  188. End Class

  189. Public Class District
  190.     Public Property districtId As String
  191.     Public Property districtName As String
  192.     Public Property provinceId As String
  193. End Class

  194. Public Class Province
  195.     Public Property provinceId As String
  196.     Public Property provinceName As String
  197. End Class

  198. Public Class LocationData
  199.     Public Property zipCode As String
  200.     Public Property subDistrictList As List(Of SubDistrict)
  201.     Public Property districtList As List(Of District)
  202.     Public Property provinceList As List(Of Province)
  203. End Class
คัดลอกไปที่คลิปบอร์ด

โค้ดในส่วนของการโปรเซสเพื่อดึงข้อมูลเข้าสู่ MS Access ... frmProcess.vb ...
  1. Imports System.ComponentModel
  2. Imports System.Data.OleDb
  3. Imports System.IO

  4. Public Class frmProcess
  5.     '// Instance Form for reference to frmJsonPostCode2Access.
  6.     Private frmJson As frmJsonPostCode2Access
  7.     '// Create BackgroundWorker.
  8.     Private WithEvents BgWorker As New BackgroundWorker()
  9.     Private Conn As New OleDbConnection
  10.     '//
  11.     Private DataBasePath As String

  12.     Public Sub AcceptFormMain(frmMain As frmJsonPostCode2Access)
  13.         frmJson = frmMain
  14.     End Sub

  15.     ' / ------------------------------------------------------------------------------------------------
  16.     Private Sub frmProcess_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
  17.         Call CreateAccessFile()
  18.         '// Initialized
  19.         With BgWorker
  20.             .WorkerReportsProgress = True
  21.             .WorkerSupportsCancellation = True
  22.         End With
  23.         '//
  24.         Control.CheckForIllegalCrossThreadCalls = False
  25.         '// Handle events
  26.         AddHandler BgWorker.DoWork, AddressOf BgWorker_DoWork
  27.         AddHandler BgWorker.ProgressChanged, AddressOf BgWorker_ProgressChanged
  28.         AddHandler BgWorker.RunWorkerCompleted, AddressOf BgWorker_RunWorkerCompleted
  29.         '// Trigger the background worker when a button is clicked or when your task starts.
  30.         BgWorker.RunWorkerAsync()
  31.     End Sub

  32.     ' / ------------------------------------------------------------------------------------------------
  33.     Sub CreateAccessFile()
  34.         '// Declare variable for Save File Dialog in Run Time.
  35.         Dim dlgSaveFile As SaveFileDialog = New SaveFileDialog()
  36.         '// Setting up Save File Dialog.
  37.         With dlgSaveFile
  38.             .InitialDirectory = MyPath(Application.StartupPath) & "data"
  39.             .Title = "Create MS Access File"
  40.             .Filter = "MS Access Files (*.accdb)|*.accdb"
  41.             .FilterIndex = 1
  42.             .RestoreDirectory = True
  43.         End With
  44.         Try
  45.             '/ If you select the OK button after Browse ...
  46.             If dlgSaveFile.ShowDialog() = DialogResult.OK Then
  47.                 Dim strCon As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & dlgSaveFile.FileName & ";"
  48.                 Call CreateDatabase(dlgSaveFile.FileName)
  49.                 '// Create a connection to the new database
  50.                 Conn = New OleDbConnection(strCon)
  51.                 Conn.Open()
  52.                 '// Create a table and columns in the new database.
  53.                 Call CreateTableColumn()
  54.                 Conn.Close()
  55.                 Conn = Nothing
  56.                 '//
  57.                 DataBasePath = dlgSaveFile.FileName
  58.             End If
  59.         Catch ex As Exception
  60.             MessageBox.Show(ex.Message)
  61.         End Try

  62.     End Sub

  63.     ' / ------------------------------------------------------------------------------------------------
  64.     Private Sub CreateDatabase(DatabasePath As String)
  65.         '// If the file exists, delete it.
  66.         If File.Exists(DatabasePath) Then File.Delete(DatabasePath)
  67.         '// Add COM Microsoft Ext. 6.0 for DLL and Security.
  68.         '// Create the new Access database.
  69.         Dim Cat As New ADOX.Catalog()
  70.         Cat.Create("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & DatabasePath & ";Jet OLEDB:Engine Type=5")
  71.         Cat = Nothing
  72.     End Sub

  73.     ' / ------------------------------------------------------------------------------------------------
  74.     Private Sub CreateTableColumn()
  75.         '// Create a table and Columns.
  76.         Dim CreateTableSQL As String = _
  77.             "CREATE TABLE PostCodeThailand (" &
  78.             "PostCodeID SMALLINT PRIMARY KEY, " &
  79.             "SubDistrictName TEXT(100), " &
  80.             "DistrictName TEXT(100), " &
  81.             "ProvinceName TEXT(100), " &
  82.             "PostCode TEXT(5))"
  83.         Dim Cmd As New OleDbCommand(CreateTableSQL, Conn)
  84.         Cmd.ExecuteNonQuery()
  85.     End Sub

  86.     ' / ------------------------------------------------------------------------------------------------
  87.     ' / Export to MS Access.
  88.     ' / ------------------------------------------------------------------------------------------------
  89.     Private Sub BgWorker_DoWork(sender As Object, e As DoWorkEventArgs)
  90.         Dim Cmd As OleDbCommand
  91.         Dim Statement As String
  92.         Dim strConn As String = _
  93.             " Provider=Microsoft.ACE.OLEDB.12.0;" & _
  94.             " Data Source = " & DataBasePath & ";" & _
  95.             " Persist Security Info=False;"
  96.         Try
  97.             'Opening the connection
  98.             Conn = New OleDb.OleDbConnection(strConn)
  99.             Conn.Open()
  100.             ' / เก็บค่า Primary Key (PostCodeID)
  101.             Dim iRow As Integer = 0
  102.             Dim MaxValue As Int16 = frmJson.dgvData.RowCount
  103.             ' / Collection of rows in the DataGridView control
  104.             For Each row As DataGridViewRow In frmJson.dgvData.Rows
  105.                 '// Store query to a variable(sql).
  106.                 Statement = _
  107.                     "INSERT INTO PostCodeThailand (PostCodeID, PostCode, SubDistrictName, DistrictName, ProvinceName ) VALUES (" _
  108.                 & "'" & iRow + 1 & "','" _
  109.                 & CStr(row.Cells(0).FormattedValue) & "','" _
  110.                 & CStr(row.Cells(1).FormattedValue) & "','" _
  111.                 & CStr(row.Cells(2).FormattedValue) & "','" _
  112.                 & CStr(row.Cells(3).FormattedValue) & "')"
  113.                 '// Set your SQL COMMANDS
  114.                 Cmd = New OleDbCommand(Statement, Conn)
  115.                 ' / Execute the Data
  116.                 Cmd.ExecuteNonQuery()
  117.                 ' / Next row
  118.                 iRow = iRow + 1
  119.                 '// ProgressBar Percentage.
  120.                 Dim progressPercentage As Integer = CInt((iRow / MaxValue) * 100)
  121.                 BgWorker.ReportProgress(progressPercentage)
  122.                 lblProgress.Text = ProgressBar1.Value & "%"
  123.                 lblCount.Text = iRow & "/" & MaxValue & " Records."
  124.             Next
  125.             Cmd = Nothing
  126.             Conn.Close()
  127.             Conn = Nothing
  128.         Catch ex As Exception
  129.             MessageBox.Show(ex.ToString)
  130.         End Try
  131.     End Sub

  132.     Private Sub BgWorker_ProgressChanged(sender As Object, e As ProgressChangedEventArgs)
  133.         '// Update the progress bar based on the reported progress.
  134.         ProgressBar1.Value = e.ProgressPercentage
  135.     End Sub

  136.     Private Sub BgWorker_RunWorkerCompleted(sender As Object, e As RunWorkerCompletedEventArgs)
  137.         '// Handle any post-processing after the background worker completes.
  138.         MessageBox.Show("Done Complete.", "Report Status", MessageBoxButtons.OK, MessageBoxIcon.Information)
  139.         Me.Dispose()
  140.         Me.Close()
  141.     End Sub

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

โมดูลฟังค์ชั่น ... modFunction.vb ...
  1. Module modFunction

  2.     ' / --------------------------------------------------------------------------------
  3.     ' / Get my project path
  4.     ' / AppPath = C:\My Project\bin\debug
  5.     ' / Replace "\bin\debug" with ""
  6.     ' / Return : C:\My Project\
  7.     Function MyPath(ByVal AppPath As String) As String
  8.         '/ Return Value
  9.         MyPath = AppPath.ToLower.Replace("\bin\debug", "").Replace("\bin\release", "").Replace("\bin\x86\debug", "")
  10.         '// If not found folder then put the \ (BackSlash) at the end.
  11.         If Microsoft.VisualBasic.Right(MyPath, 1) <> Chr(92) Then MyPath = MyPath & Chr(92)
  12.     End Function
  13. End Module
คัดลอกไปที่คลิปบอร์ด

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

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

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

x
สิ่งที่ดีกว่าการให้ คือการให้แบบไม่มีที่สิ้นสุด
ขออภัย! คุณไม่ได้รับสิทธิ์ในการดำเนินการในส่วนนี้ กรุณาเลือกอย่างใดอย่างหนึ่ง ลงชื่อเข้าใช้ | ลงทะเบียน

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

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

GMT+7, 2024-4-30 03:53 , Processed in 0.306144 second(s), 4 queries , File On.

Powered by Discuz! X3.4, Rev.62

Copyright © 2001-2020 Tencent Cloud.

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