SqlBulkCopy ColumnMapping Argumentexception

时间:2014-03-28 06:23:14

标签: csv sqlbulkcopy columnmappings

下面的代码给了我一个争论,说明源csv中明显存在的源列' e_partnerid'并不存在。我有一种感觉,Delimiter没有设置正确或类似的东西,我尝试更改一点连接字符串,但我仍然得到相同的错误。

static DataTable GetDataTableFromCsv(string path, string csvSelection, bool isFirstRowHeader)
    {
        string header = isFirstRowHeader ? "Yes" : "No";


        string pathOnly = Path.GetDirectoryName(path);
        string fileName = Path.GetFileName(path);
        //string sql = @"SELECT " + csvSelection + " FROM [" + fileName + "];";
        string sql = @"SELECT " + "*" + " FROM [" +  fileName  + "];";

        using (OleDbConnection connection = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + pathOnly + ";Extended Properties=\"Text;HDR=" + header + ";FMT=Delimited(;)\""))
        using (OleDbCommand command = new OleDbCommand(sql, connection))
        using (OleDbDataAdapter adapter = new OleDbDataAdapter(command))
        {
            DataTable dataTable = new DataTable();
            dataTable.Locale = CultureInfo.CurrentCulture;
            adapter.Fill(dataTable);
            return dataTable;
        }

    }

我用;作为csv内部的Delimiter甚至将它设置在connstring中,但仍然是同样的异常。

1 个答案:

答案 0 :(得分:0)

我需要创建一个描述列的schema.ini:

private static void writeSchema(DataColumnCollection columns, string csvDir, string csvFileName)
    {
        FileStream fsOutput =
                 new FileStream(csvDir + "\\schema.ini",
                                     FileMode.Create, FileAccess.Write);
        StreamWriter srOutput = new StreamWriter(fsOutput);

        srOutput.WriteLine("[" + csvFileName + "]");
        int i = 1;
        foreach (DataColumn item in columns)
        {
            srOutput.WriteLine("Col" + i + "=\"" + item.ToString() + "\" Text");
            i++;
        }
        srOutput.Close();
        fsOutput.Close();
    }