【发布时间】: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 -
是的,我在另一个屏幕上打开了一个文本编辑器,以查看运行代码时发生的情况,并在文本文件中显示标题。