【问题标题】:How do you read a CSV file and display the results in a grid in Visual Basic 2010?如何在 Visual Basic 2010 中读取 CSV 文件并在网格中显示结果?
【发布时间】:2011-03-29 23:46:51
【问题描述】:

如何在 Visual Basic 2010 中读取 CSV 文件并在网格中显示结果?这听起来很简单,但我在谷歌搜索了一段时间后仍然找不到答案。我在表单上有 DataGridView,它被称为 DataGridView1。我有一个只有 3 列数据的 CSV,我希望能够显示它们。

【问题讨论】:

标签: vb.net visual-studio-2010 datagrid csv


【解决方案1】:

考虑一下这段代码。根据您的需要进行修改,或根据您的要求进行修改。您需要为System.IOSystem.Data.OleDb 提供Imports 语句。

Dim fi As New FileInfo("c:\foo.csv")
Dim connectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties=Text;Data Source=" & fi.DirectoryName

Dim conn As New OleDbConnection(connectionString)
conn.Open()

'the SELECT statement is important here, 
'and requires some formatting to pull dates and deal with headers with spaces.
Dim cmdSelect As New OleDbCommand("SELECT Foo, Bar, FORMAT(""SomeDate"",'YYYY/MM/DD') AS SomeDate, ""SOME MULTI WORD COL"", FROM " & fi.Name, conn)

Dim adapter1 As New OleDbDataAdapter
adapter1.SelectCommand = cmdSelect

Dim ds As New DataSet
adapter1.Fill(ds, "DATA")

myDataGridView.DataSource = ds.Tables(0).DefaultView 
myDataGridView.DataBind
conn.Close()

【讨论】:

  • 您正在使用数据库引擎来解析 CSV 文件?这似乎是超级骗人的矫枉过正。至少代码很短:)
  • @Meryln:谢谢,我想。不确定通过 OleDb/Jet 查询可能被认为是过度杀伤力。据我估计,过度杀伤将是 Excel COM API。 OP 对性能、优雅、酷炫或企业模式没有任何要求。这只是一个建议。期待您的解决方案。
  • 谢谢大家,我会试试看
  • @Merlyn, @p.campbell OleDB/Jet 可以被认为是矫枉过正,因为微软已经在 .Net 框架中构建了一个class for reading CSV files
  • 你摇滚!感谢您的帮助
【解决方案2】:

考虑这篇 CodeProject 文章/项目:LINQ TO CSV

它将使您能够创建一个形状类似于 .csv 文件列的自定义类。然后,您将使用 CSV 并绑定到您的 DataGridView。

Dim cc As new CsvContext()
Dim inputFileDescription As New CsvFileDescription() With { _
    .SeparatorChar = ","C, _
    .FirstLineHasColumnNames = True _
}

Dim products As IEnumerable(Of Product) = _
     cc.Read(Of Product)("products.csv", inputFileDescription)

' query from CSV, load into a new class of your own   
Dim productsByName = From p In products
    Select New CustomDisplayClass With _
       {.Name = p.Name, .SomeDate = p.SomeDate, .Price = p.Price}, _        
    Order By p.Name


myDataGridView1.DataSource = products
myDataGridView1.DataBind()

【讨论】:

    【解决方案3】:

    使用 .Net 框架中内置的 TextFieldParser 类。

    这是从 Paul Clement 的 MSDN forum post 复制的一些代码。它将 CSV 转换为新的内存中 DataTable,然后将 DataGridView 绑定到 DataTable

        Dim TextFileReader As New Microsoft.VisualBasic.FileIO.TextFieldParser("C:\Documents and Settings\...\My Documents\My Database\Text\SemiColonDelimited.txt")
    
        TextFileReader.TextFieldType = FileIO.FieldType.Delimited
        TextFileReader.SetDelimiters(";")
    
        Dim TextFileTable As DataTable = Nothing
    
        Dim Column As DataColumn
        Dim Row As DataRow
        Dim UpperBound As Int32
        Dim ColumnCount As Int32
        Dim CurrentRow As String()
    
        While Not TextFileReader.EndOfData
            Try
                CurrentRow = TextFileReader.ReadFields()
                If Not CurrentRow Is Nothing Then
                    ''# Check if DataTable has been created
                    If TextFileTable Is Nothing Then
                        TextFileTable = New DataTable("TextFileTable")
                        ''# Get number of columns
                        UpperBound = CurrentRow.GetUpperBound(0)
                        ''# Create new DataTable
                        For ColumnCount = 0 To UpperBound
                            Column = New DataColumn()
                            Column.DataType = System.Type.GetType("System.String")
                            Column.ColumnName = "Column" & ColumnCount
                            Column.Caption = "Column" & ColumnCount
                            Column.ReadOnly = True
                            Column.Unique = False
                            TextFileTable.Columns.Add(Column)
                        Next
                    End If
                    Row = TextFileTable.NewRow
                    For ColumnCount = 0 To UpperBound
                        Row("Column" & ColumnCount) = CurrentRow(ColumnCount).ToString
                    Next
                    TextFileTable.Rows.Add(Row)
                End If
            Catch ex As _
            Microsoft.VisualBasic.FileIO.MalformedLineException
                MsgBox("Line " & ex.Message & _
                "is not valid and will be skipped.")
            End Try
        End While
        TextFileReader.Dispose()
        frmMain.DataGrid1.DataSource = TextFileTable
    

    【讨论】:

    • TextFileReader.SetDelimeters(new string() {";"}) 愿这对任何人都有帮助,因为它帮助了我
    【解决方案4】:
    For Each line As String In System.IO.File.ReadAllLines("D:\abc.csv")
        DataGridView1.Rows.Add(line.Split(","))
    Next
    

    【讨论】:

      【解决方案5】:

      这看起来更优雅一点

      'populate DT from .csv file
      
       Dim items = (From line In IO.File.ReadAllLines("C:YourData.csv") _
       Select Array.ConvertAll(line.Split(","c), Function(v) _ 
       v.ToString.TrimStart(""" ".ToCharArray).TrimEnd(""" ".ToCharArray))).ToArray
      
      Dim Your_DT As New DataTable
      For x As Integer = 0 To items(0).GetUpperBound(0)
      Your_DT.Columns.Add()
      Next
      
      For Each a In items
      Dim dr As DataRow = Your_DT.NewRow
      dr.ItemArray = a
      Your_DT.Rows.Add(dr)
      Next
      
      Your_DataGrid.DataSource = Your_DT           
      

      【讨论】:

        【解决方案6】:

        这是您可以使用OLEDB 提供程序从.csv 文件中读取数据的方法。

          If OpenFileDialog1.ShowDialog(Me) = DialogResult.OK Then
                Try
                    Dim fi As New FileInfo(OpenFileDialog1.FileName)
                    Dim sConnectionStringz As String = "Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties=Text;Data Source=" & fi.DirectoryName
                    Dim objConn As New OleDbConnection(sConnectionStringz)
                    objConn.Open()
                    'DataGridView1.TabIndex = 1
                    Dim objCmdSelect As New OleDbCommand("SELECT * FROM " & fi.Name, objConn)
                    Dim objAdapter1 As New OleDbDataAdapter
                    objAdapter1.SelectCommand = objCmdSelect
                    Dim objDataset1 As New DataSet
                    objAdapter1.Fill(objDataset1)
        
                    '--objAdapter1.Update(objDataset1) '--updating
                    DataGridView1.DataSource = objDataset1.Tables(0).DefaultView
                Catch ex as Exception
                   MsgBox("Error: " + ex.Message)
                Finally
                    objConn.Close()
                End Try
            End If
        

        【讨论】:

          【解决方案7】:

          执行以下操作:

          Dim dataTable1 As New DataTable
                          dataTable1.Columns.Add("FECHA")
                          dataTable1.Columns.Add("TT")
                          dataTable1.Columns.Add("DESCRIPCION")
                          dataTable1.Columns.Add("No. DOC")
                          dataTable1.Columns.Add("DEBE")
                          dataTable1.Columns.Add("HABER")
                          dataTable1.Columns.Add("SALDO")
          
          For Each line As String In System.IO.File.ReadAllLines(objetos.url)
                              dataTable1.Rows.Add(line.Split(","))
                          Next
          

          【讨论】:

          • 你能用数据表吗:)
          猜你喜欢
          • 2013-03-29
          • 2010-11-05
          • 2011-05-27
          • 2014-06-09
          • 2017-08-02
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多