Skip to content

Instantly share code, notes, and snippets.

@dj1711572002
Last active October 29, 2020 08:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dj1711572002/95c81b628d1a54c4c31209aed0d74ef9 to your computer and use it in GitHub Desktop.
Save dj1711572002/95c81b628d1a54c4c31209aed0d74ef9 to your computer and use it in GitHub Desktop.
VB.NET DataGridView test CSV file read
Imports Microsoft.VisualBasic.FileIO
Imports System.Text
Imports System.IO
Public Class Form1
Public i, j, k As Integer
'=============CSV Save======================
Public file As System.IO.StreamWriter
Public file1 As System.IO.StreamWriter
Public readata(10000, 1000) As String
Public cIndex, cIndex_max As Integer
'====FILE Headers =============================
Public fname As String
Public chname(17) As String
Public wakuch(17) As String
Public wakuN(6) As String
'===============DataGridView用パラメータ==========
Public Path As String '= "D:\Temp\TestData.csv" 'CsvファイルのPathを指定
Public Path_1 As String '1個前のファイル名
Public kaishiKeta As Integer = 1 ' データ配列書き込み開始列数
'==================Data Array========================
Public rIndex As Integer
Public kajyuN As Integer
'waku1,2,3(荷重No,結果No)=correl,slope,intercept,X軸値mV、Y軸値mV
'chdata(荷重No,CHNo)=CH1-CH16
Public waku1(200, 7) As Double
Public waku2(200, 7) As Double
Public waku3(200, 7) As Double
Public chdata(200, 17) As Double
Public dgRow(17) As Double
'==================================================================================
'DataGridView全データを CSV保存
'=================================================================================
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim f1open As Integer
Dim fname1 As String
Dim fStr1 As String
Dim fStr2 As String
f1open = 0
'========First CSV File Declaration======================
If f1open = 0 Then
DataGridView1.Visible = False
RichTextBox1.Visible = True
fname1 = Format(Now, "yyyyMMdd_HHmmss")
fStr1 = "" 'ComboBox9.SelectedItem.ToString()
fname1 = "C:\vb_LOG\" & fStr1 & fname1 & ".csv"
fStr2 = "FileOpen:" + fname1
RichTextBox1.AppendText(fStr2)
RichTextBox1.ScrollToCaret()
'---MS Example------------------------------
'Dim file As System.IO.StreamWriter
'file = My.Computer.FileSystem.OpenTextFileWriter("c:\test.txt", True)
'file.WriteLine("Here is the first string.")
'file.Close()
'------------------------------------------
Dim enc As System.Text.Encoding = System.Text.Encoding.GetEncoding(“Shift_JIS”)
file1 = My.Computer.FileSystem.OpenTextFileWriter(fname1, False, enc)
f1open = 1
'---------定義されたサイズ全体を保存する--------------------
For i = 0 To DataGridView1.RowCount - 1
For j = 0 To DataGridView1.ColumnCount - 1
Dim sdata = CStr(DataGridView1.Rows(i).Cells(j).Value) + ","
file1.Write(sdata)
Next j
file1.Write(vbCrLf)
Next i
file1.Close()
'file1.Write(ch_namestr & vbCr)
'file1.Write("waku1:," & TextBox22.Text & "chX," & TextBox23.Text & "chY,waku2:," & TextBox24.Text & "chX," & TextBox25.Text & "chY,waku3:," & TextBox26.Text & "chX," & TextBox27.Text & "chY" & vbCr)
'file1.Write("wakuNo,kajyuNo,correl,slope,intercept,X,Y" & vbCr)
End If
End Sub
'=================FILE OPEN FIleReading DGVへ自動追記========================
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'==========================================================================
'==============--一般のCSVファイル読み込みDGV===================================
'==========================================================================
Dim datasu As Integer
Dim counter As Integer
Dim maxRowCSV As Integer
DataGridView1.ColumnCount = 30
If CheckBox1.Checked = True Then
DataGridView1.Visible = True
RichTextBox1.Visible = False
DataGridView1.Rows.Clear()
Path = readCSV() 'Dialogから読み込むファイル名指定
Label3.Text = Path
maxRowCSV = GetLinesOfTextFile(Path)
Label1.Text = CStr(maxRowCSV) & "行"
DataGridView1.RowCount = maxRowCSV
'RichTextBox1.AppendText("maxRow=" & CStr(maxRowCSV))
Label2.Text = "CSV File Reading"
datasu = CSV_crlf(Path)
Label2.Text = "CSV File Read Finished"
If cIndex_max > DataGridView1.ColumnCount Then
DataGridView1.ColumnCount = cIndex_max
End If
'=========CSVから全データ配列 redata(maxRowCSV,cIndex)==========
rIndex += 1
For i = 0 To maxRowCSV - 1
For j = 1 To readata(i, 0) '1その行の列数は、readata(行,0)に格納されている
'Debug.Print("DGV_rdata(" & CStr(i) & "," & CStr(j) & ")=" & CStr(readata(i, j)))
DataGridView1.Rows(i).Cells(j).Value = readata(i, j)
Next j
Next i
End If
'=================================================================================
'=================校正測定Color File 用DGV===================================================
If CheckBox1.Checked = False Then
DataGridView1.Visible = True
RichTextBox1.Visible = False
'DataGridView1.Columns.Clear()
'=======ダイアログで指定したColorファイル名を返す==========
Path = readCSV()
'====ファイルデータを読み込んで配列fname,chname(),wakuch(),wakuN()chdata(,),waku1(,),waku2(,),waku3(,)にする=======
ColordataSort(Path)
'===================================================================
'================Input file dataArrays to DataGridView ==============
DataGridView1.ColumnCount = 30
DataGridView1.RowCount = 200
'DataGridView1.Columns.Clear()
'-----ROW1=chname()----------------
If rIndex = 0 Then
For i = 0 To 16
DataGridView1.Rows(0).Cells(i + kaishiKeta).Value = chname(i)
Next
End If
If Path_1 <> Path Then
Path_1 = Path
DataGridView1.Rows(rIndex + 1).Cells(0).Value = Path
End If
'-----関数 dgv_Input_cdata(chdata名,荷重水準数,現在の行No=rIndex)------
rIndex = dgv_Input_chdata(chdata, kajyuN, rIndex)
'DataGridView1.Rows(rIndex + 1).Cells(0).Value = rIndex
'rIndex = dgv_Input_chdata(chdata, kajyuN, rIndex)
End If
End Sub
'=========================================================================
'================校正測定ColorFileでDataGridViewへ2次元配列を代入===============================
'=========================================================================
Private Function dgv_Input_chdata(ByRef dary(,) As Double, kajN As Integer, startindex As Integer) As Integer
Dim Rowindex As Integer
'-----ROw2以降 chdata 荷重水準数kajyuNだけ代入-----
DataGridView1.Rows.Add(1)
For i = 1 To kajyuN
'Rowindex = DataGridView1.Rows.Count - 1
DataGridView1.Rows(startindex + i).Cells(0 + kaishiKeta).Value = startindex + i
''DataGridView1.Rows(行番号).Cells(列番号).Value = 値」でセルの値を設定しています。
For k = 1 To 16 'Column count
' DataGridView1.Rows.Add(chdata(i, k))
DataGridView1.Rows(startindex + i).Cells(k + kaishiKeta).Value = chdata(i, k + 1)
Next
Rowindex += 1
Next i
Return Rowindex + rIndex
End Function
'=================================================================================
'=============================校正測定ColorFileからヘッダー読み出し ===========
'=================================================================================
Private Sub ColordataSort(fnm As String)
Dim SR As New StreamReader(fnm) 'StreamReader
Dim linebuf As String 'データ保持用
'DataGrid初期化
'校正測定ファイルより1行読込(ヘッダー行)
While k = 0
linebuf = SR.ReadLine()
Dim str() As String = linebuf.Split(",")
j += 1 'line No increment
Debug.Print("lineNo=" & CStr(j) & "str(0)=" & str(0))
'====srt(0)の最初の6文字でデータ判別=====================
Select Case j 'str(0).Substring(0, 6)
Case 1 '"FileOp"
fname = str(0)
Debug.Print("fname=" & fname)
Case 2 ' "dataNo"
Debug.Print("chname:")
For i = 0 To str.Length - 1
chname(i) = str(i)
Debug.Print("," & CStr(chname(i)))
Next
Case 3 '"waku1:"
Debug.Print("In wakuch:str(1)=" & str(0))
Debug.Print("wakuch:")
For i = 0 To str.Length - 1
wakuch(i) = str(i)
Debug.Print("," & CStr(wakuch(i)))
Next i
Case 4 '"wakuNo"
Debug.Print("In wakuNo:str(1)=" & str(0))
Debug.Print("wakuN:")
For i = 0 To str.Length - 1
wakuN(i) = str(i)
Debug.Print("," & CStr(wakuN(i)))
Next i
Case Else
k = 1
End Select
'Debug.Print(CStr(i) & ":" & linebuf)
'If str(0) = "waku1:" Then
' k = 1
'End If
End While
If k = 1 Then
Do
'Csvファイルよりdata列読込み
linebuf = SR.ReadLine()
'データが無ければループ終了
If linebuf = Nothing Then Exit Do
Dim RowArr() As String = linebuf.Split(",")
makeAry(RowArr) 'ColorFIleのデータを各配列に振り分け
Loop
End If
SR.Close()
End Sub
'======================================================================================
'======================== 校正測定ColorFileからデータ部分を配列化=====================
'====ファイルデータを読み込んで配列fname,chname(),wakuch(),wakuN()chdata(,),waku1(,),waku2(,),waku3(,)にする=======
Private Function makeAry(strAry As String())
'=======================Array def=================================
Dim strL As Integer
Dim loadNo As Integer
strL = strAry.Length
Select Case strAry(0)
Case "waku1:"
loadNo = strAry(1)
Debug.Print("Array_waku1=" & CStr(strL))
For i = 2 To strL - 1
waku1(loadNo, i - 1) = CDbl(strAry(i))
Debug.Print("waku1(" & CStr(loadNo) & "," & CStr(i - 1) & ")=" & CStr(waku1(loadNo, i - 1)))
Next i
Case "waku2:"
loadNo = strAry(1)
Debug.Print("Array_waku2=" & CStr(strL))
For i = 2 To strL - 1
waku2(loadNo, i - 1) = CDbl(strAry(i))
Debug.Print("waku2(" & CStr(loadNo) & "," & CStr(i - 1) & ")=" & CStr(waku2(loadNo, i - 1)))
Next i
Case "waku3:"
loadNo = strAry(1)
Debug.Print("Array_waku3=" & CStr(strL))
For i = 2 To strL - 1
waku3(loadNo, i - 1) = CDbl(strAry(i))
Debug.Print("waku3(" & CStr(loadNo) & "," & CStr(i - 1) & ")=" & CStr(waku3(loadNo, i - 1)))
Next i
Case "CH:"
loadNo = strAry(1)
kajyuN = loadNo
Debug.Print("Array_CH=" & CStr(strL))
For i = 2 To strL - 1
If strAry(i) <> "" Then
chdata(loadNo, i - 1) = CDbl(strAry(i))
Debug.Print("chdata(" & CStr(loadNo) & "," & CStr(i - 1) & ")=" & CStr(chdata(loadNo, i - 1)))
End If
Next i
End Select
End Function
'============================================================================
'=========-ダイアログを開いて校正測定ColorFileを指定してファイル名を戻す====================
'============================================================================
Private Function readCSV() As String
Dim ofd As New OpenFileDialog()
'はじめのファイル名を指定する
'はじめに「ファイル名」で表示される文字列を指定する
ofd.FileName = "yyyyMMdd_HHmmss" '"default.html"
'はじめに表示されるフォルダを指定する
'指定しない(空の文字列)の時は、現在のディレクトリが表示される
ofd.InitialDirectory = "C:\vb_LOG "
'[ファイルの種類]に表示される選択肢を指定する
'指定しないとすべてのファイルが表示される
ofd.Filter = "TXTファイル|*.txt|CSVファイル|*.csv|すべてのファイル|*.*"
'[ファイルの種類]ではじめに選択されるものを指定する
'2番目の「すべてのファイル」が選択されているようにする
ofd.FilterIndex = 2
'タイトルを設定する
ofd.Title = "開くファイルを選択してください"
'ダイアログボックスを閉じる前に現在のディレクトリを復元するようにする
ofd.RestoreDirectory = True
'存在しないファイルの名前が指定されたとき警告を表示する
'デフォルトでTrueなので指定する必要はない
ofd.CheckFileExists = True
'存在しないパスが指定されたとき警告を表示する
'デフォルトでTrueなので指定する必要はない
ofd.CheckPathExists = True
If ofd.ShowDialog() = DialogResult.OK Then
'OKボタンがクリックされたとき、選択されたファイル名を表示する
Debug.Print(ofd.FileName)
RichTextBox1.AppendText(ofd.FileName)
End If
'ダイアログを表示する
'================================MS sample=========================
'https://docs.microsoft.com/ja-jp/dotnet/visual-basic/developing-apps/programming/drives-directories-files/how-to-read-from-comma-delimited-text-files
'===================================================================
Return ofd.FileName
End Function
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
rIndex = 0 ' DGVの初期行番号
End Sub
'==========================================================================================
'===================CSV crlf FILE Read Function=================================================
'======================================================================================
Private Function CSV_crlf(ByVal fnm As String) As Integer '戻り値はデータ数
Dim rdataN As Integer
Using parser As New TextFieldParser(fnm, System.Text.Encoding.GetEncoding("Shift_JIS"))
parser.TextFieldType = FieldType.Delimited
parser.SetDelimiters(",") ' 区切り文字はコンマ
' parser.HasFieldsEnclosedInQuotes = False
' parser.TrimWhiteSpace = False
cIndex = 0
rdataN = 0
While Not parser.EndOfData
Dim row As String() = parser.ReadFields() ' 1行読み込み
For Each field As String In row
cIndex += 1
readata(rdataN, cIndex) = field
Debug.Print("Function_field=" & field)
Debug.Print("Function_readata(" & CStr(cIndex) & ")=" & CStr(readata(rdataN, cIndex)))
RichTextBox1.AppendText(field + ",")
'RichTextBox1.AppendText(field + vbTab) ' TAB区切りで出力
Next
readata(rdataN, 0) = cIndex 'その行の要素数をゼロ番目に書き込む
'RichTextBox1.AppendText(vbCrLf)
If cIndex > cIndex_max Then
cIndex_max = cIndex
End If
cIndex = 0
rdataN += 1
End While
End Using
Return rdataN
End Function
'============================CSVファイル 総行数カウントFunction==============================
Public Function GetLinesOfTextFile(ByVal FileName As String) As Integer
Dim StReader As New System.IO.StreamReader(FileName)
Dim LineCount As Integer
While (StReader.Peek() >= 0)
StReader.ReadLine()
LineCount += 1
End While
Return LineCount
End Function
End Class
'Private Function CSV(ByVal FileName As String) As Integer
' 'RichTextBox1.Visible = True
' 'DataGridView1.Visible = False
' Using MyReader As New Microsoft.VisualBasic.FileIO.TextFieldParser(FileName)
' MyReader.TextFieldType = FileIO.FieldType.Delimited
' MyReader.SetDelimiters(",")
' Dim currentRow As String()
' cIndex = 0
' While Not MyReader.EndOfData
' Try
' currentRow = MyReader.ReadFields()
' Dim currentField As String
' For Each currentField In currentRow
' 'MsgBox(currentField)
' readata(cIndex) = currentField
' 'Debug.Print(cIndex & ":" & readata(cIndex))
' 'RichTextBox1.AppendText(readata(cIndex) & ",")
' cIndex = cIndex + 1
' 'If cIndex > 1000 Then Exit Sub
' Next
' Catch ex As Microsoft.VisualBasic.
' FileIO.MalformedLineException
' MsgBox("Line " & ex.Message &
' "is not valid and will be skipped.")
' End Try
' End While
' End Using
' Return cIndex
'End Function
'Dim SR As New StreamReader(fnm) 'StreamReader
'Dim linebuf As String 'データ保持用
'Dim i, j, n As Integer
'Dim Hexstr As String
'Do
' 'Csvファイルよりdata列読込み
' linebuf = SR.ReadLine()
' n += 1
' 'データが無ければループ終了
' If linebuf = Nothing Then Exit Do
' Dim RowArr() As String = linebuf.Split(",")
' For i = 0 To RowArr.Length - 1
' For j = 0 To RowArr(i).Length - 1
' Dim c1 As Char = RowArr(i).Chars(j)
' Hexstr = Hex(Asc(c1)) + ","
' 'If Hexstr = "\n" Then
' ' Hexstr = Hexstr + vbCrLf
' 'Else
' ' Hexstr = Hexstr + "," 'CStr(Asc(c1)) + ","
' 'End If
' RichTextBox1.AppendText(Hexstr)
' Next j
' Next i
'Loop
'Return n
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment