[VB.NET] การแยกชุดข้อมูลออกจากกันด้วยเครื่องหมายหลายแบบด้วย TextFieldParser
http://www.g2gnet.com/webboard/images/vbnet/ParserText.pngเวลาที่เราทำการแยกแยะข้อมูล (Parser) ด้วยเครื่องหมาย หรือสัญลักษณ์ที่คั่นอยู่ระหว่างข้อมูล (Delimited) ในเท็กซ์ไฟล์ ปกติก็มักจะเจอกับรูปแบบตัวแยกที่แน่นอนตายตัว คือมีแค่แบบเดียว เช่น เครื่องหมายคอมม่า (,) หรือช่องว่าง อย่างใดอย่างหนึ่ง เรียกได้ว่าหากินกันง่ายๆสบายๆ แต่ทว่าบางครั้งชุดข้อมูลมันก็มาแบบแปลกๆ คือมีสารพัดตัวแยกนี่ซิ แล้วจะทำอย่างไร??? วันนี้แอดมินเลยมาขอนำเสนอความเก่งของ VB.Net คือการใช้ TextFieldParser ดังต่อไปนี้ ...
มาดูโค้ดกันเถอะ ...
' / --------------------------------------------------------------------
' / Developer : Mr.Surapon Yodsanga (Thongkorn Tubtimkrob)
' / eMail : thongkorn@hotmail.com
' / URL: http://www.g2gnet.com (Khon Kaen - Thailand)
' / Facebook: https://www.facebook.com/g2gnet (For Thailand)
' / Facebook: https://www.facebook.com/commonindy (Worldwide)
' / Purpose: Process a delimited file with many signs.
' / Microsoft Visual Basic .NET (2010)
' /
' / This is open source code under @CopyLeft by Thongkorn Tubtimkrob.
' / You can modify and/or distribute without to inform the developer.
' / --------------------------------------------------------------------
'Imports System.IO
Public Class frmParserText
Private strFile As String = String.Empty
Private Sub frmParserText_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Call SetupDGVData()
End Sub
Private Sub btnImport_Click(sender As System.Object, e As System.EventArgs) Handles btnImport.Click
Dim OpenFile As New OpenFileDialog()
' ระบุ Path เริ่มต้น (Initial) โดยผมเลือกตำแหน่งของโปรเจคปัจจุบัน
OpenFile.InitialDirectory = MyPath(Application.StartupPath)
OpenFile.FileName = ""
' กำหนดให้เลือกกรอง (Filter) เฉพาะเท็กซ์ไฟล์ (Text File)
OpenFile.Filter = "Text File (*.txt)|*.txt"
' http://msdn.microsoft.com/en-us/library/c7ykbedk.aspx
' http://msdn.microsoft.com/en-us/library/system.windows.forms.dialogresult.aspx
' .NET มีดีอย่างตรงที่ไม่ต้องเรียก Component มาใช้งาน
Dim Res As System.Windows.Forms.DialogResult = OpenFile.ShowDialog()
' มีการกด Cancel ให้ออกไปเลย ... ดีกว่า VB6 เยอะเลยแบบนี้ ... ยอมรับ - Accept
If Res = System.Windows.Forms.DialogResult.Cancel Then Return
'// เรียกไฟล์ตัวอย่าง
strFile = IO.Path.Combine(OpenFile.FileName)
dgvData.Rows.Clear()
'// เริ่มต้นทำการแยกข้อมูล
Call ParserText()
End Sub
' / --------------------------------------------------------------------
' / Parser Text with delimited.
Private Sub ParserText()
'// ประกาศ reader ให้เป็นการอ่านข้อมูลเพื่อทำการแยก (TextFieldParser)
Dim reader As Microsoft.VisualBasic.FileIO.TextFieldParser = My.Computer.FileSystem.OpenTextFieldParser(strFile)
'// กำหนด reader ด้วย TextFieldType เพื่อทำการแยกชุดข้อมูลออกจากกัน
reader.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.Delimited
'// ตั้งค่าให้ reader แยกชุดข้อมูลด้วเครื่องหมายคอมม่า (,) Tap และไปป์ (|)
reader.Delimiters = New String() {",", vbTab, "|"}
'// กรณีที่บรรทัดนั้นมีเครื่องหมาย // ก็ไม่ต้องไปสนใจมัน หรือข้ามมันไปเลย
reader.CommentTokens = New String() {"//"}
'// วนรอบการอ่านข้อมูลทีละบรรทัด
Do While Not reader.EndOfData
Try
'// แยกชุดข้อมูลออกจากกันทีละบรรทัดด้วยการใช้ ReadFields method
Dim arrFields As String() = reader.ReadFields()
'//
Dim dgvRow As New DataGridViewRow
Dim dgvCell As DataGridViewCell
'// แยกข้อมูลออกมาทีละหลัก
For Each strField As String In arrFields
'// รับค่าเข้ามาทีละเซลล์ (ไฟล์ตัวอย่างมี 3 หลัก)
dgvCell = New DataGridViewTextBoxCell
dgvCell.Value = strField
dgvRow.Cells.Add(dgvCell)
Next
'// เพิ่มเข้าไปในแถวของตารางกริด
dgvData.Rows.Add(dgvRow)
'// Trap Error
Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
MessageBox.Show(ex.Message)
End Try
Loop
'// Close the reader
reader.Close()
End Sub
' / --------------------------------------------------------------------------------
'// Initialize DataGridView @Run Time
Private Sub SetupDGVData()
With dgvData
.RowHeadersVisible = False
.AllowUserToAddRows = False
.AllowUserToDeleteRows = False
.AllowUserToResizeRows = False
.MultiSelect = False
.SelectionMode = DataGridViewSelectionMode.FullRowSelect
.ReadOnly = True
.Font = New Font("Tahoma", 9)
' Columns Specified
.Columns.Add("ID", "ID")
.Columns.Add("Name", "Name")
.Columns.Add("Point", "Point")
' Autosize Column
.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill
.AutoResizeColumns()
'// Even-Odd Color
.AlternatingRowsDefaultCellStyle.BackColor = Color.AliceBlue
' Adjust Header Styles
With .ColumnHeadersDefaultCellStyle
.BackColor = Color.Navy
.ForeColor = Color.Black
.Font = New Font("Tahoma", 9, FontStyle.Bold)
End With
End With
End Sub
' / --------------------------------------------------------------------------------
' / Get my project path
' / AppPath = C:\My Project\bin\debug
' / Replace "\bin\debug" with "\"
' / Return : C:\My Project\
Function MyPath(ByVal AppPath As String) As String
'/ MessageBox.Show(AppPath);
AppPath = AppPath.ToLower()
'/ Return Value
MyPath = AppPath.Replace("\bin\debug", "\").Replace("\bin\release", "\")
'// If not found folder then put the \ (BackSlash) at the end.
If Microsoft.VisualBasic.Right(MyPath, 1) <> "\" Then MyPath = MyPath & "\"
End Function
Private Sub btnExit_Click(sender As System.Object, e As System.EventArgs) Handles btnExit.Click
Me.Close()
End Sub
Private Sub frmParserText_FormClosed(sender As Object, e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
Me.Dispose()
Application.Exit()
End Sub
End Class
ดาวน์โหลดโค้ดต้นฉบับ VB.NET (2010) ได้ที่นี่ ขอบคุณครับ
หน้า:
[1]