输入数组长于此表中的列数。 例外

我正在使用以下代码来读取CSV文件内容。

http://www.sendspace.com/file/l0zki3链接下载CSV文件..

这是CSV文件,位于我的C:\ Drive中。

我得到的例外是“输入数组长于此表中的列数”。 为什么会这样?

using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.IO; //stremreader.. is frm.. System.IO.. .. namespace csvtodatagridview { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void ShowData() { Boolean flg=true; string deli = ","; string tbname = "Booktb"; //dataset .. used 2 stored. then move dataset to .. grid.. string filename = ("C:\\SharedIncidents.csv"); // path. plz keep the same path. .. string str = Convert.ToString(System.DateTime.Now); DataSet ds = new DataSet(); StreamReader sr = new StreamReader(filename); //Inputoutput .function 2 read.. file.. ds.Tables.Add(tbname); //add 2 table.. ds.Tables[tbname].Columns.Add("Date"); //specify. colum1 for datagrid1. ds.Tables[tbname].Columns.Add("Status" );//specify colum2 for datagrid2. ds.Tables[tbname].Columns.Add("Assignee" ); ds.Tables[tbname].Columns.Add("Response" ); string alldata = sr.ReadToEnd(); string[] rows = alldata.Split("\n".ToCharArray()); foreach (string r in rows) { string[] items = r.Split(deli.ToCharArray()); ds.Tables[tbname].Rows.Add(items); } int count = ds.Tables[tbname].Rows.Count; int index = 0; int currentindex = 0; for (index = 0; index < count; index++) { if (ds.Tables[tbname].Rows[index][0].Equals(str)) { flg = true; DataSet ds1 = new DataSet(); ds1.Tables.Add(tbname); ds1.Tables[tbname].Columns.Add("Date"); //specify. colum1 for datagrid1. ds1.Tables[tbname].Columns.Add("Status");//specify colum2 for datagrid2. ds1.Tables[tbname].Columns.Add("Assignee"); ds1.Tables[tbname].Columns.Add("Response"); currentindex = index; while (currentindex < count) { DataRow row = ds.Tables["tbname"].Rows[currentindex]; ds1.Tables[tbname].Rows.Add(row); currentindex++; } break; } } if (flg == false) Console.WriteLine("Date not matched"); else this.dataGridView1.DataSource = ds.Tables[0].DefaultView; } private void button1_Click(object sender, EventArgs e) { ShowData(); // call the abv function. . } } } 

没有看到输入数据(或至少是它的样本)很难回答。 但是,假设CSV中的“逗号”表示“下一个字段”是正确的; 可能会引用数据,例如:

 123, "Gravell, Marc", 1324 

我会从这里推荐CSV阅读器 ,这是正确的。

你的“CSV拆分” 只是在逗号上分开,忽略引号之类的东西。 你也是

例如,这是您文件中的一行:

 ,frgv,gthbgtb,"be bm,k," 

目前,这将分为:

 1. (empty string) 2. frgv 3. gthbgtb 4. "be bm 5. k 6 " 

这比你想要的更多。 最后三个应该都是一个值,其中包含逗号。 您需要使解析步骤更加智能,逐步完成字符串并记住它是否在引用区域中。 (或者像Marc建议的那样使用第三方库。)

听起来你的行中包含一个额外的分隔符,导致它将其拆分为一个额外的列。 你可以张贴文件的样本来检查出来。

编辑:是的,在查看您的文件后,我可以在响应字段中看到一些额外的逗号,这些逗号会导致这些逗号被拆分。 因此,要么考虑使用不同的字符来拆分,要么在响应列之后对数组中的所有项目进行连接,并手动将项目添加到表中。