Your browser (Internet Explorer 6) is out of date. It has known security flaws and may not display all features of this and other websites. Learn how to update your browser.
X
Articoli

Modulo per la lettura/scrittura di file csv in vb.net

Scrivo questa nota più come appunto personale più che per reale utilità da parte di alcuni lettori (o forse no…non si sa mai).

Comunque ho dovuto fare un programma che legge, elabora e riscrive file .csv (quelli di excel per intenderci). Il modulo che presento qui contiene 2 funzioni: la prima serve a importare un file .csv all’interno di un array bidimensionale per permetterne l’elaborazione mentre, la seconda, serve a prendere i dati di un array bidimensionale e esportarlo come file .csv . Non posto spiegazioni per il momento, ma se vi interessa sarò felice di rispondere alle vostre domande sui commenti (il codice comunque è semplice e si dovrebbe spiegare da se anche se purtroppo non posso inserire le indentature).


Imports System.IO

Module Module2

 Public Sub csv_parsing(ByVal csv_file As String, ByVal array(,) As String)

 Dim riga As String = ""
 Dim testo As String = ""
 Dim lettera As String
 Dim k As Integer
 Dim x As Integer
 Dim y As Integer

 Dim readFile As System.IO.TextReader = New StreamReader(csv_file)

 While True
 riga = readFile.ReadLine()
 If riga Is Nothing Then
 Exit While
 Else
 k = 1
 While True
 lettera = Mid(riga, k, 1)
 If lettera = "" Then
 array(y, x) = testo
 testo = ""
 x = 0
 Exit While
 Else
 If lettera = ";" Then
 array(y, x) = testo
 testo = ""
 k = k + 1
 x = x + 1
 Else
 testo = testo + lettera
 k = k + 1
 End If
 End If

 End While
 y = y + 1
 End If
 End While
 readFile.Close()

 End Sub

 Public Sub csv_write(ByVal array(,) As String, ByVal nomefile As String)

 Dim cella As String = "asd"
 Dim k As Integer
 Dim linea As String
 Dim correggi As Integer = 0

 Using writer As StreamWriter = New StreamWriter(nomefile)
 Do While cella <> Nothing

 linea = ""
 cella = array(k, 0)
 For x = 0 To array.GetUpperBound(0)
 linea = linea & array(k, x) & " ; "
 Next
 writer.WriteLine(linea)
 k = k + 1
 Loop
 writer.Close()
 End Using

 End Sub

End Module