我試圖將CSV文件導入到我的C#站點並將其保存在數據庫中。在做研究時,我瞭解了CSV解析,我試圖實現這一點,但我遇到了一些麻煩。這裏是我的代碼的一部分至今:解析C#中的CSV文件時遇到的問題#
string fileext = Path.GetExtension(fupcsv.PostedFile.FileName);
if (fileext == ".csv")
{
string csvPath = Server.MapPath("~/CSVFiles/") + Path.GetFileName(fupcsv.PostedFile.FileName);
fupcsv.SaveAs(csvPath);
// Add Columns to Datatable to bind data
DataTable dtCSV = new DataTable();
dtCSV.Columns.AddRange(new DataColumn[2] { new DataColumn("ModuleId", typeof(int)), new DataColumn("CourseId", typeof(int))});
// Read all the lines of the text file and close it.
string[] csvData = File.ReadAllLines(csvPath);
// iterate over each row and Split it to New line.
foreach (string row in csvData)
{
// Check for is null or empty row record
if (!string.IsNullOrEmpty(row))
{
using (TextFieldParser parser = new TextFieldParser(csvPath))
{
parser.TextFieldType = FieldType.Delimited;
parser.SetDelimiters(",");
while (!parser.EndOfData)
{
//Process row
string[] fields = parser.ReadFields();
int i = 1;
foreach (char cell in row)
{
dtCSV.NewRow()[i] = cell;
i++;
}
}
}
}
}
}
我不斷收到錯誤「沒有排在位置1」在「dtCSV.Rows [dtCSV.Rows.Count - 1] [i] =細胞;」 任何幫助將不勝感激,謝謝
將是所有變化如果可以發佈整個例外,並且如果可能的話,鏈接到您嘗試使用代碼的csv文件時,效果會更好。 –
將該行添加到數據表中,然後將值分配給它的行。 –
該例外的第一部分是「在System.Data.dll中發生類型'System.IndexOutOfRangeException'的異常,但未在用戶代碼中處理」。不知道如何放csv文件,但它只有兩行關閉數字 –