我想導入一個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++;
}
}
}`
也許你的字段中有一個''',在其內部會導致你的一行有11個字段(或者更多),這會導致你的代碼崩潰,出現這樣的錯誤代碼。 – litelite
如果你有十列,它們將在C#數組中被引用爲0到9,而不是1到10. –
@litelite我有美元值存儲在其中一列有「,」 –