Visual Basic 如何读取 CSV 文件并在数据网格中显示值?

发布于 2024-07-24 13:16:44 字数 298 浏览 6 评论 0原文

我正在使用 VB 2005,如何打开 CSV 文件并读取列/行并在数据网格中显示值?

CSV 文件示例: jsmith,[email protected]

然后我想对每一行执行一个操作即每个用户,我该怎么做?

正如你所知,我是一个新手,但很乐意学习。

谢谢

I'm using VB 2005, how do I open a CSV file and read the columns/rows and display the values in a datagrid?

CSV file example:
jsmith,[email protected]

I then want to perform an action on each row i.e. each user, how would I do this?

I'm a newbie as you can tell but happy to learn.

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

北陌 2024-07-31 13:16:45

使用 TextFieldParser ,即 内置于 VB.NET。 Google 找到了我这个示例

Using MyReader As New Microsoft.VisualBasic.FileIO.TextFieldParser _
  ("C:\test\info.csv")

  'Specify that reading from a comma-delimited file'
  MyReader.TextFieldType = FileIO.FieldType.Delimited
  MyReader.SetDelimiters(",")

  Dim currentRow As String()
  While Not MyReader.EndOfData
    Try
      currentRow = MyReader.ReadFields()
      With Me.dgvReport.Rows
        .Add(currentRow) 'Add new row to data grid view'
     End With
   Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
     MsgBox("Line " & ex.Message & _
       "is not valid and will be skipped.")
   End Try
 End While
End Using

Use the TextFieldParser that's built into VB.NET. Google found me this example

Using MyReader As New Microsoft.VisualBasic.FileIO.TextFieldParser _
  ("C:\test\info.csv")

  'Specify that reading from a comma-delimited file'
  MyReader.TextFieldType = FileIO.FieldType.Delimited
  MyReader.SetDelimiters(",")

  Dim currentRow As String()
  While Not MyReader.EndOfData
    Try
      currentRow = MyReader.ReadFields()
      With Me.dgvReport.Rows
        .Add(currentRow) 'Add new row to data grid view'
     End With
   Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
     MsgBox("Line " & ex.Message & _
       "is not valid and will be skipped.")
   End Try
 End While
End Using
哥,最终变帅啦 2024-07-31 13:16:45

下面是一个使用 ADO.Net 的 ODBC 文本驱动程序的简单解决方案:

Dim csvFileFolder As String = "C:\YourFileFolder"
Dim csvFileName As String = "YourFile.csv"

'Note that the folder is specified in the connection string,
'not the file. That's specified in the SELECT query, later.
Dim connString As String = "Driver={Microsoft Text Driver (*.txt; *.csv)};Dbq=" _
    & csvFileFolder & ";Extended Properties=""Text;HDR=No;FMT=Delimited"""

Dim conn As New Odbc.OdbcConnection(connString)

'Open a data adapter, specifying the file name to load
Dim da As New Odbc.OdbcDataAdapter("SELECT * FROM [" & csvFileName & "]", conn)
'Then fill a data table, which can be bound to a grid
Dim dt As New DataTable
da.Fill(dt)

grdCSVData.DataSource = dt

填充后,您可以对数据表的属性(如 ColumnName)进行赋值,以利用 ADO.Net 数据对象的所有功能。

在VS2008中你可以使用Linq来达到同样的效果。

Here's a simple solution that uses ADO.Net's ODBC text driver:

Dim csvFileFolder As String = "C:\YourFileFolder"
Dim csvFileName As String = "YourFile.csv"

'Note that the folder is specified in the connection string,
'not the file. That's specified in the SELECT query, later.
Dim connString As String = "Driver={Microsoft Text Driver (*.txt; *.csv)};Dbq=" _
    & csvFileFolder & ";Extended Properties=""Text;HDR=No;FMT=Delimited"""

Dim conn As New Odbc.OdbcConnection(connString)

'Open a data adapter, specifying the file name to load
Dim da As New Odbc.OdbcDataAdapter("SELECT * FROM [" & csvFileName & "]", conn)
'Then fill a data table, which can be bound to a grid
Dim dt As New DataTable
da.Fill(dt)

grdCSVData.DataSource = dt

Once filled, you can value properties of the datatable, like ColumnName, to make utilize all the powers of the ADO.Net data objects.

In VS2008 you can use Linq to achieve the same effect.

谁把谁当真 2024-07-31 13:16:45

用途:

Dim reader As New Common.CSVReader("C:\MyFile.txt")
reader.DisplayResults(dgvMyView)

类别:

Imports System.Windows.Forms
Imports System.IO
Imports System.Text.RegularExpressions

Public Class CSVReader
    Private Const ESCAPE_SPLIT_REGEX = "({1}[^{1}]*{1})*(?<Separator>{0})({1}[^{1}]*{1})*"
    Private FieldNames As String()
    Private Records As List(Of String())
    Private ReadIndex As Integer 

    Public Sub New(File As String)
        Records = New List(Of String())
        Dim Record As String()
        Dim Reader As New StreamReader(File)
        Dim Index As Integer = 0
        Dim BlankRecord As Boolean = True 

        FieldNames = GetEscapedSVs(Reader.ReadLine())
        While Not Reader.EndOfStream
            Record = GetEscapedSVs(Reader.ReadLine())
            BlankRecord = True
            For Index = 0 to Record.Length - 1
                If Record(Index) <> "" Then BlankRecord = False 
            Next
            If Not BlankRecord Then Records.Add(Record)
        End While
        ReadIndex = -1
        Reader.Close()
    End Sub

    Private Function GetEscapedSVs(Data As String, Optional Separator As String = ",", Optional Escape As String = """") As String()
        Dim Result As String()      
        Dim Index As Integer
        Dim PriorMatchIndex As Integer = 0
        Dim Matches As MatchCollection = _
            Regex.Matches(Data, String.Format(ESCAPE_SPLIT_REGEX, Separator, Escape))

        ReDim Result(Matches.Count)

        For Index = 0 to Result.Length - 2
            Result(Index) = Data.Substring(PriorMatchIndex, Matches.Item(Index).Groups("Separator").Index - PriorMatchIndex)
            PriorMatchIndex = Matches.Item(Index).Groups("Separator").Index + Separator.Length
        Next
        Result(Result.Length - 1) = Data.Substring(PriorMatchIndex)

        For Index = 0 To Result.Length - 1
            If Regex.IsMatch(Result(Index), String.Format("^{0}[^{0}].*[^{0}]{0}$", Escape)) Then _
    Result(Index) = Result(Index).Substring(1, Result(Index).Length - 2)
            Result(Index) = Replace(Result(Index), Escape & Escape, Escape)
            If Result(Index) Is Nothing Then Result(Index) = ""
        Next

        GetEscapedSVs = Result 
    End Function

    Public ReadOnly Property FieldCount As Integer 
        Get
            Return FieldNames.Length 
        End Get
    End Property

    Public Function GetString(Index As Integer) As String
        Return Records(ReadIndex)(Index)
    End Function

    Public Function GetName(Index As Integer) As String
        Return FieldNames(Index)
    End Function

    Public Function Read() As Boolean
        ReadIndex = ReadIndex + 1
        Return ReadIndex < Records.Count 
    End Function


    Public Sub DisplayResults(DataView As DataGridView)
        Dim col As DataGridViewColumn
        Dim row As DataGridViewRow
        Dim cell As DataGridViewCell
        Dim header As DataGridViewColumnHeaderCell
        Dim Index As Integer
        ReadIndex = -1

        DataView.Rows.Clear()
        DataView.Columns.Clear()

        For Index = 0 to FieldCount - 1
            col = new DataGridViewColumn()
            col.CellTemplate = new DataGridViewTextBoxCell()
            header = new DataGridViewColumnHeaderCell()
            header.Value = GetName(Index)
            col.HeaderCell = header
            DataView.Columns.Add(col)
        Next 

        Do While Read()
            row = new DataGridViewRow()
            For Index = 0 to FieldCount - 1
                cell = new DataGridViewTextBoxCell()
                cell.Value = GetString(Index).ToString()
                row.Cells.Add(cell)
            Next
            DataView.Rows.Add(row)
        Loop
    End Sub
End Class

Usage:

Dim reader As New Common.CSVReader("C:\MyFile.txt")
reader.DisplayResults(dgvMyView)

Class:

Imports System.Windows.Forms
Imports System.IO
Imports System.Text.RegularExpressions

Public Class CSVReader
    Private Const ESCAPE_SPLIT_REGEX = "({1}[^{1}]*{1})*(?<Separator>{0})({1}[^{1}]*{1})*"
    Private FieldNames As String()
    Private Records As List(Of String())
    Private ReadIndex As Integer 

    Public Sub New(File As String)
        Records = New List(Of String())
        Dim Record As String()
        Dim Reader As New StreamReader(File)
        Dim Index As Integer = 0
        Dim BlankRecord As Boolean = True 

        FieldNames = GetEscapedSVs(Reader.ReadLine())
        While Not Reader.EndOfStream
            Record = GetEscapedSVs(Reader.ReadLine())
            BlankRecord = True
            For Index = 0 to Record.Length - 1
                If Record(Index) <> "" Then BlankRecord = False 
            Next
            If Not BlankRecord Then Records.Add(Record)
        End While
        ReadIndex = -1
        Reader.Close()
    End Sub

    Private Function GetEscapedSVs(Data As String, Optional Separator As String = ",", Optional Escape As String = """") As String()
        Dim Result As String()      
        Dim Index As Integer
        Dim PriorMatchIndex As Integer = 0
        Dim Matches As MatchCollection = _
            Regex.Matches(Data, String.Format(ESCAPE_SPLIT_REGEX, Separator, Escape))

        ReDim Result(Matches.Count)

        For Index = 0 to Result.Length - 2
            Result(Index) = Data.Substring(PriorMatchIndex, Matches.Item(Index).Groups("Separator").Index - PriorMatchIndex)
            PriorMatchIndex = Matches.Item(Index).Groups("Separator").Index + Separator.Length
        Next
        Result(Result.Length - 1) = Data.Substring(PriorMatchIndex)

        For Index = 0 To Result.Length - 1
            If Regex.IsMatch(Result(Index), String.Format("^{0}[^{0}].*[^{0}]{0}$", Escape)) Then _
    Result(Index) = Result(Index).Substring(1, Result(Index).Length - 2)
            Result(Index) = Replace(Result(Index), Escape & Escape, Escape)
            If Result(Index) Is Nothing Then Result(Index) = ""
        Next

        GetEscapedSVs = Result 
    End Function

    Public ReadOnly Property FieldCount As Integer 
        Get
            Return FieldNames.Length 
        End Get
    End Property

    Public Function GetString(Index As Integer) As String
        Return Records(ReadIndex)(Index)
    End Function

    Public Function GetName(Index As Integer) As String
        Return FieldNames(Index)
    End Function

    Public Function Read() As Boolean
        ReadIndex = ReadIndex + 1
        Return ReadIndex < Records.Count 
    End Function


    Public Sub DisplayResults(DataView As DataGridView)
        Dim col As DataGridViewColumn
        Dim row As DataGridViewRow
        Dim cell As DataGridViewCell
        Dim header As DataGridViewColumnHeaderCell
        Dim Index As Integer
        ReadIndex = -1

        DataView.Rows.Clear()
        DataView.Columns.Clear()

        For Index = 0 to FieldCount - 1
            col = new DataGridViewColumn()
            col.CellTemplate = new DataGridViewTextBoxCell()
            header = new DataGridViewColumnHeaderCell()
            header.Value = GetName(Index)
            col.HeaderCell = header
            DataView.Columns.Add(col)
        Next 

        Do While Read()
            row = new DataGridViewRow()
            For Index = 0 to FieldCount - 1
                cell = new DataGridViewTextBoxCell()
                cell.Value = GetString(Index).ToString()
                row.Cells.Add(cell)
            Next
            DataView.Rows.Add(row)
        Loop
    End Sub
End Class
荒岛晴空 2024-07-31 13:16:45

使用图书馆为您阅读。

CsvHelper(我维护的库)可通过 NuGet 获取。

我对VB不熟悉,所以如果有人想把它改成VB,请这样做。 不过,这只是几行代码。

var streamReader = // Create StreamReader to CSV file.
var csvReader = new CsvReader( streamReader );
var myObjects = csvReader.GetRecords<MyObject>();
// You can then databind the myObjects collection to a datagrid.
// If you don't want the whole file, you can read row by row.
var myObject = csvReader.GetRecord<MyObject>();

Use a library to do the reading for you.

CsvHelper (a library I maintain) is available via NuGet.

I'm not familiar with VB, so if anyone wants to change this into VB, please do. Though, it's only a few lines of code.

var streamReader = // Create StreamReader to CSV file.
var csvReader = new CsvReader( streamReader );
var myObjects = csvReader.GetRecords<MyObject>();
// You can then databind the myObjects collection to a datagrid.
// If you don't want the whole file, you can read row by row.
var myObject = csvReader.GetRecord<MyObject>();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文