【问题标题】:Importing csv file to datatable returns no results将 csv 文件导入数据表不会返回任何结果
【发布时间】:2010-11-15 06:26:20
【问题描述】:

此方法不会引发异常,也不会从读取到 DataTable 的 csv 文件中返回行。我为自己做错了而不知所措。

非常感谢任何帮助。

public string ImportCsvFile(string filePath)
    {
        FileInfo file = new FileInfo(filePath);
        //string connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\"" + file.DirectoryName + "\" Extended Properties='text;HDR=Yes;FMT=Delimited(,)';";
        string connString = string.Format(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};" + @" Extended Properties={1}", file.DirectoryName, "'Text;HDR=YES;FMT=CSVDelimited'");
        using (OleDbConnection con = new OleDbConnection(connString))
        {
            OleDbCommand cmd = new OleDbCommand(string.Format("SELECT * FROM [{0}]", file.Name), con);
            // Using a DataTable to process the data
            try
            {
                con.Open();
                ds = new DataTable("MyTable");
                OleDbDataAdapter adp = new OleDbDataAdapter(cmd);
                adp.Fill(ds);
                foreach (DataRow row in ds.Rows)
                {
                    System.Diagnostics.Debug.WriteLine(row.ToString());
                }
            }
            catch (Exception error)
            {
                String errorString;
                errorString = "Error occurred while importing data from source file." + System.Environment.NewLine +
                "Error Message: " + error.Message + System.Environment.NewLine +
                "Stack Trace: " + error.StackTrace;
                return errorString;
            }                    
        }
        return "File imported to DataTable";
    }

【问题讨论】:

  • 这里只是一个刺,但我没有看到 con.close()。
  • 使用“使用”语句,您不需要 .Close() 调用。它将关闭并处理连接。

标签: .net sql datatable oledb


【解决方案1】:

事实证明,这段代码很好。这里的问题是 csv 文件。存在某种类型的文件损坏或文件格式不兼容。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-27
    • 1970-01-01
    • 1970-01-01
    • 2022-01-09
    • 2020-09-12
    • 1970-01-01
    相关资源
    最近更新 更多