2017-08-14 27 views
0

我想導入一個CSV文件到我的數據庫。該文件有10列。只是用於測試目的,我第一隻杉杉進口4列,它工作得很好,但是當我嘗試導入所有列我得到一個錯誤說找不到列10錯誤:找不到列10

這是我的代碼

`

 DataTable dt = new DataTable(); 
     dt.Columns.AddRange(new DataColumn[10] { new DataColumn("Invoice", typeof(string)), 
     new DataColumn("P.O.Number", typeof(string)), 
     new DataColumn("Line", typeof(int)), 
     new DataColumn("Invoice_Date",typeof(DateTime)), 
     new DataColumn("Gross", typeof(string)), 
     new DataColumn("Disc", typeof(string)), 
     new DataColumn("NET", typeof(string)), 
     new DataColumn("Date_PD", typeof(string)), 
     new DataColumn("Check#_Doc#", typeof(string)), 
     new DataColumn("Additional_Info", typeof(string))}); 


     string csvData = File.ReadAllText(csvPath); 
     foreach (string row in csvData.Split('\n')) 
     { 
      if (!string.IsNullOrEmpty(row)) 
      { 
       dt.Rows.Add(); 
       int i = 0; 
       foreach (string cell in row.Split(',')) 
       { 
        dt.Rows[dt.Rows.Count - 1][i] = cell; 
        i++; 
       } 
      } 
     }` 
+3

也許你的字段中有一個''',在其內部會導致你的一行有11個字段(或者更多),這會導致你的代碼崩潰,出現這樣的錯誤代碼。 – litelite

+0

如果你有十列,它們將在C#數組中被引用爲0到9,而不是1到10. –

+0

@litelite我有美元值存儲在其中一列有「,」 –

回答

0

您的列索引從0開始,並以9結尾而非10. 您試圖添加一個不存在的列索引。

int i = 0; 
foreach (string cell in row.Split(',')) 
{ 
    if(i == 10) 
     throw new ArgumentOutOfRangeException(nameof(i)); 


    dt.Rows[dt.Rows.Count - 1][i] = cell; 
    i++; 
} 

異常將阻止壞的數據被寫入到數據源,如果你在你的源額外,逗號。

我建議投資時間將源代碼轉換爲|由管道分隔的文件作爲,逗號可以在數據本身中常用。

+0

但是,如果一個字段包含',',數據將被加載到錯誤的字段中。有些會被默默地忽略 – litelite

+0

是的,這就是發生了什麼 –

+0

同意,理想的方法是使用庫來管理CSV數據,請參閱 - https://stackoverflow.com/questions/1941392/are-there-any- csv-readers-writer-libraries-in -c'Josh Close'推薦'CsvHelper',它是一個易於使用的CSV庫。 – Nova