Importare il contenuto di un file CSV in un DataGrid
Private Sub (string filename)
Dim ConnectionString As String = "Driver={Microsoft Text Driver (*.txt; *.csv)};Dbq=" & _
Server.MapPath("tmp_excel/") & ";"
Dim csvConnection As OdbcConnection = New OdbcConnection(ConnectionString)
csvConnection.Open()
Try
Dim csvCommand As OdbcCommand
Dim csvReader As OdbcDataReader
'DataTable per la lettura dei dati da .CSV
Dim dt As DataTable = New DataTable
dt.Columns.Add(New DataColumn("campo1"))
dt.Columns("campo1").DataType = System.Type.GetType("System.String")
dt.Columns.Add(New DataColumn("campo2"))
dt.Columns("campo2").DataType = System.Type.GetType("System.String")
'Leggo il file .CSV
csvCommand = csvConnection.CreateCommand()
csvCommand.CommandText = "select * from [" & filename & "]"
csvCommand.CommandType = CommandType.Text
csvReader = csvCommand.ExecuteReader()
Try
Do While csvReader.Read()
' Carico i dati nel DataTable
Dim drNew As DataRow = dt.NewRow()
drNew(0) = csvReader(0).ToString().Trim()
drNew(1) = csvReader(1).ToString().Trim()
dt.Rows.Add(drNew)
Loop
Finally
csvReader.Close()
End Try
Dim aDV As DataView = New DataView(dt)
'Collego la sorgente dati al datagrid
myDataGrid.DataSource = aDV
myDataGrid.DataBind()
Finally
csvConnection.Close()
End Try
End Sub