C#将CSV插入SQL

时间:2017-03-10 22:15:30

标签: c# sql csv sqlbulkcopy

我正在尝试将CS​​V数据导入SQL,但是当我查看程序尝试导入的内容时,它会在第一行和第一列之后停止。我假设它正在尝试将其添加为标题,我可以跳过列标题还是需要添加?感谢

private static DataTable csvDataTable(string filepath)
    {
        DataTable csvData = new DataTable();
        try
        {
            using (TextFieldParser csvReader = new TextFieldParser(filepath))
            {
                csvReader.SetDelimiters(new string[] { "," });
                csvReader.HasFieldsEnclosedInQuotes = false;

                string[] colFields = csvReader.ReadFields();
                foreach (string column in colFields)
                {
                    DataColumn datecolumn = new DataColumn(column);
                    datecolumn.AllowDBNull = true;
                    csvData.Columns.Add(datecolumn);
                }
                while (!csvReader.EndOfData)
                {
                    string[] fieldData = csvReader.ReadFields();

                    for (int i = 0; i < fieldData.Length; i++)
                    {
                        if (fieldData[i] == "")
                        {
                            fieldData[i] = null;
                        }
                    }
                    csvData.Rows.Add(fieldData);
                }
            }
        }
        catch (Exception ex)
        {
        }
        return csvData;
    }

0 个答案:

没有答案