【问题标题】:Import and Export csv File from DataGridView从 DataGridView 导入和导出 csv 文件
【发布时间】:2018-10-03 17:40:08
【问题描述】:

高,我目前正在为一个大学项目制作一个小软件,该项目的目标是让用户导入原料和信息,然后他们可以用这些原料制作饭菜。

我遇到了一个问题,但在我使用该软件一次添加新成分后加载 csv 文件时出现错误:“System.IndexOutOfRangeException: 'Index was outside the数组的边界。'" 并突出显示代码部分 "newRow("Protien") = columns(1)" 现在我认为是因为当它加载数据时从最近保存的 csv 文件中,顶部有一行填充了标题,有什么方法可以保存 csv 文件而不包括数据表中的标题?

在 csv 文件中加载的代码:

 'Sets up the data table that will be used to store the ingredients and their information.'
    With ingredientTable
        .Columns.Add("Name", System.Type.GetType("System.String"))
        .Columns.Add("Protien", System.Type.GetType("System.Decimal"))
        .Columns.Add("Fat", System.Type.GetType("System.Decimal"))
        .Columns.Add("Salt", System.Type.GetType("System.Decimal"))
        .Columns.Add("Carbs", System.Type.GetType("System.Decimal"))
        .Columns.Add("Calories", System.Type.GetType("System.Decimal"))
    End With

    'Loads in the information from the CSV file to display all the previouly saved ingredients'
    Dim fileReader As New IO.StreamReader("C:\Users\Grant\Desktop\FitnessAppNew\Save Files\Saved_Ingredients.csv", System.Text.Encoding.Default)
    Dim ingredientString As String = ""

    Do

        ingredientString = fileReader.ReadLine
        If ingredientString Is Nothing Then Exit Do
        'Reads what is on the CSV file and sets up the columns and the rows.' 
        Dim columns() As String = ingredientString.Split(",")
        Dim newRow As DataRow = ingredientTable.NewRow
        newRow("Name") = columns(0)
        newRow("Protien") = columns(1)
        newRow("Fat") = columns(2)
        newRow("Salt") = columns(3)
        newRow("Carbs") = columns(4)
        newRow("Calories") = columns(5)
        ingredientTable.Rows.Add(newRow)
    Loop
    fileReader.Close()

    DataGridView1.DataSource = ingredientTable
    Me.Text = ingredientTable.Rows.Count & "rows"

保存 CSV 文件的代码:

Private Sub Button7_Click(sender As Object, e As EventArgs) Handles Button7.Click

#Region "Save ingredients"
    Dim csvFile As String = String.Empty

    csvFile = csvFile.TrimEnd(",")
    csvFile = csvFile & vbCr & vbCrLf

    'Used to ge the rows
    For Each row As DataGridViewRow In DataGridView1.Rows
        'Used to get each cell in the row
        For Each cell As DataGridViewCell In row.Cells
            csvFile = csvFile & cell.FormattedValue & ","
        Next
        csvFile = csvFile.TrimEnd(",")
        csvFile = csvFile & vbCr & vbCrLf
    Next
    My.Computer.FileSystem.WriteAllText("C:\Users\Grant\Desktop\FitnessAppNew\Save Files\Saved_Ingredients.csv", csvFile, False)


#End Region

【问题讨论】:

  • Now I think is because ... 你不能用记事本打开它并确定吗? 我们当然不能。该代码中没有显示任何内容来编写标题,因此不太可能。手动解析 CSV 充满了危险,因此最好使用库来为您解析。请阅读How to Ask 并采取tour
  • 是的,我在另一个屏幕上打开了一个文本编辑器,以查看运行代码时发生的情况,并在文本文件中显示标题。

标签: vb.net csv import export


【解决方案1】:

以下是一些可供考虑的选项,用于将数据从 CSV 加载到 DGV。

Imports System.Data.SqlClient
Imports System.IO
Imports Microsoft.VisualBasic.FileIO
Imports System.Data
Imports System.Data.Odbc
Imports System.Data.OleDb


Public Class Form1
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click


        Dim headers = (From header As DataGridViewColumn In DataGridView1.Columns.Cast(Of DataGridViewColumn)() Select header.HeaderText).ToArray
        Dim rows = From row As DataGridViewRow In DataGridView1.Rows.Cast(Of DataGridViewRow)() Where Not row.IsNewRow Select Array.ConvertAll(row.Cells.Cast(Of DataGridViewCell).ToArray, Function(c) If(c.Value IsNot Nothing, c.Value.ToString, ""))
        Dim str As String = ""
        Using sw As New IO.StreamWriter("C:\Users\Excel\Desktop\OrdersTest.csv")
            sw.WriteLine(String.Join(",", headers))
            'sw.WriteLine(String.Join(","))
            For Each r In rows
                sw.WriteLine(String.Join(",", r))
            Next
            sw.Close()
        End Using

    End Sub

    Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
        'Dim m_strConnection As String = "server=Excel-PC\SQLEXPRESS;Initial Catalog=Northwind;Trusted_Connection=True;"

        'Catch ex As Exception
        '    MessageBox.Show(ex.ToString())
        'End Try

        'Dim objDataset1 As DataSet()
        'Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        'Dim da As OdbcDataAdapter
        Dim OpenFile As New System.Windows.Forms.OpenFileDialog ' Does something w/ the OpenFileDialog
        Dim strFullPath As String, strFileName As String
        Dim tbFile As New TextBox
        ' Sets some OpenFileDialog box options
        OpenFile.Filter = "CSV Files (*.csv)|*.csv|All files (*.*)|*.*" ' Shows only .csv files
        OpenFile.Title = "Browse to file:" ' Title at the top of the dialog box

        If OpenFile.ShowDialog() = DialogResult.OK Then ' Makes the open file dialog box show up
            strFullPath = OpenFile.FileName ' Assigns variable
            strFileName = Path.GetFileName(strFullPath)

            If OpenFile.FileNames.Length > 0 Then ' Checks to see if they've picked a file

                tbFile.Text = strFullPath ' Puts the filename in the textbox

                ' The connection string for reading into data connection form
                Dim connStr As String
                connStr = "Driver={Microsoft Text Driver (*.txt; *.csv)}; Dbq=" + Path.GetDirectoryName(strFullPath) + "; Extensions=csv,txt "

                ' Sets up the data set and gets stuff from .csv file
                Dim Conn As New OdbcConnection(connStr)
                Dim ds As DataSet
                Dim DataAdapter As New OdbcDataAdapter("SELECT * FROM [" + strFileName + "]", Conn)
                ds = New DataSet

                Try
                    DataAdapter.Fill(ds, strFileName) ' Fills data grid..
                    DataGridView1.DataSource = ds.Tables(strFileName) ' ..according to data source

                    ' Catch and display database errors
                Catch ex As OdbcException
                    Dim odbcError As OdbcError
                    For Each odbcError In ex.Errors
                        MessageBox.Show(ex.Message)
                    Next
                End Try

                ' Cleanup
                OpenFile.Dispose()
                Conn.Dispose()
                DataAdapter.Dispose()
                ds.Dispose()

            End If
        End If

    End Sub

    Private Sub Button4_Click(sender As System.Object, e As System.EventArgs) Handles Button4.Click
        Dim tblReadCSV As New DataTable()

        tblReadCSV.Columns.Add("FName")
        tblReadCSV.Columns.Add("LName")
        tblReadCSV.Columns.Add("Department")

        Dim csvParser As New TextFieldParser("C:\Users\Excel\Desktop\Employee.txt")

        csvParser.Delimiters = New String() {","}
        csvParser.TrimWhiteSpace = True
        csvParser.ReadLine()

        While Not (csvParser.EndOfData = True)
            tblReadCSV.Rows.Add(csvParser.ReadFields())
        End While

        Dim con As New SqlConnection("Server=Excel-PC\SQLEXPRESS;Database=Northwind;Trusted_Connection=True;")
        Dim strSql As String = "Insert into Employee(FName,LName,Department) values(@Fname,@Lname,@Department)"
        'Dim con As New SqlConnection(strCon)
        Dim cmd As New SqlCommand()
        cmd.CommandType = CommandType.Text
        cmd.CommandText = strSql
        cmd.Connection = con
        cmd.Parameters.Add("@Fname", SqlDbType.VarChar, 50, "FName")
        cmd.Parameters.Add("@Lname", SqlDbType.VarChar, 50, "LName")
        cmd.Parameters.Add("@Department", SqlDbType.VarChar, 50, "Department")

        Dim dAdapter As New SqlDataAdapter()
        dAdapter.InsertCommand = cmd
        Dim result As Integer = dAdapter.Update(tblReadCSV)

    End Sub

End Class

【讨论】:

    【解决方案2】:

    你必须试试这个代码。

    打开按钮

    Dim OpenFileDialog1 As New OpenFileDialog()
        Dim constr As String
        Dim con As OleDb.OleDbConnection
    
        Try
    
            OpenFileDialog1.Filter = "Excel Files | *.xlsx; *.xls; *.xlsm;"
    
            If OpenFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
                Me.txtOpen.Text = OpenFileDialog1.FileName
    
                constr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + txtOpen.Text + ";Excel 12.0 Xml;HDR=YES"
                con = New OleDb.OleDbConnection(constr)
                con.Open()
    
                cboSheet.DataSource = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, Nothing)
                cboSheet.DisplayMember = "TABLE_NAME"
                cboSheet.ValueMember = "TABLE_NAME"
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    

    加载按钮

    Dim constr As String
        Dim dt As DataTable
        Dim con As OleDbConnection
        Dim sda As OleDbDataAdapter
        Dim row As DataRow
    
        Try
            constr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + txtOpen.Text + ";Excel 12.0 Xml;HDR=YES"
            con = New OleDbConnection(constr)
            sda = New OleDbDataAdapter("Select * from [" + cboSheet.SelectedValue + "]", con)
            dt = New DataTable
            sda.Fill(dt)
    
            For Each row In dt.Rows
                DataGridView3.DataSource = dt
    
            Next
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    

    我希望它会起作用! :)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-06-07
      • 2012-04-14
      • 2022-06-17
      • 2018-12-01
      • 2019-04-18
      • 2016-10-09
      • 1970-01-01
      • 2014-05-19
      相关资源
      最近更新 更多