2013-04-06 99 views
0

所以这是我的问题。从csv忽略一行内的逗号

我正在将CSV读取到datagridview中。 csv的第一行是列标题,文件的第一行变为行。我正在读取该文件并将其用作datagridview的数据源。然而,在CSV一些线具有类似于

name,test,1,2,3,test,2,3,2,1,test,name

凡有上述当我使用.Split()它认为它作为行中新的细胞加粗的东西但是列数是10而不是11,我也得到了以下错误:

Input array is longer than the number of columns in this table

我该如何解决这个问题。

以下是我的C#代码。

OpenFileDialog openFile = new OpenFileDialog(); 
     openFile.InitialDirectory = "c:\\"; 
     openFile.Filter = "txt files (*.txt)|*.txt| CSV Files (*.csv) | *.csv| All Files (*.*) | *.*"; 
     openFile.FilterIndex = 2; 
     openFile.RestoreDirectory = true; 
     try { 
      if (openFile.ShowDialog() == DialogResult.OK) 
      { 
       string file = openFile.FileName; 
       StreamReader sr = new StreamReader(file); 

       /* gets all the lines of the csv */ 
       string[] str = File.ReadAllLines(file); 

       /* creates a data table*/ 
       DataTable dt = new DataTable(); 

       /* gets the column headers from the first line*/ 
       string[] temp = str[0].Split(','); 

       /* creates columns of the gridview base on what is stored in the temp array */ 
       foreach (string t in temp) 
       { 
        dt.Columns.Add(t, typeof(string)); 
       } 

       /* retrieves the rows after the first row and adds it to the datatable */ 
       for (int i = 1; i < str.Length; i++) 
       { 
        string[] t = str[i].Split(','); 
        dt.Rows.Add(t); 
       } 

       /* assigns the data grid view a data source based on what is stored in dt */ 
       dataGridView1.DataSource = dt; 
      } 
     } 
     catch (Exception ex) 
     { 
       MessageBox.Show("Error: The CSV you selected could not be loaded" + ex.Message); 
     } 
+0

@SteveWellens这是关于引号内的逗号。这里似乎没有任何引用,除非OP忘了它们。 – svick 2013-04-06 00:56:19

回答

1

这听起来更像是一个数据问题,而不是编程问题。如果你的CSV文件应该有10列,但有一些有11列,你怎么知道哪一列是额外的列?

你可以做的一件事是检查添加行之前的列数。

for (int i = 1; i < str.Length; i++) 
{ 
    string[] t = str[i].Split(','); 
    if(t.Length == temp.Length) 
     dt.Rows.Add(t); 
} 
相关问题