c# - 将 csv 加载到 oleDB 中并将所有推断的数据类型强制为字符串

标签 c# csv oledb connection-string

我正在尝试使用 oledb 将 csv 文件加载到数据表中。

这没问题,但不幸的是,其中一个看起来是数字的字段在大约 3% 的字段中有一个字符串值,因此没有被填充。

因为我正在将 csv 转换为 xml,所以我真的不关心推断数据类型,只需要字符串中的数据,因为我可以稍后在 Linq2XMl 阶段转换它。

我希望能够在连接字符串中做到这一点。

我不想只复制表格,用我想要的数据类型设置新列,然后将数据写入其中,因为这将涉及加载 csv 文件两次。

有什么想法吗?

我当前的连接字符串是

Provider=Microsoft.Jet.OLEDB.4.0;Data Source="+ thefile.DirectoryName + ";Extended Properties='text;HDR=Yes;FMT=Delimited'";

最佳答案

做了一些研究,答案是使用 schema.ini 但为您的数据集动态生成它。

http://msdn.microsoft.com/en-us/library/ms709353(VS.85).aspx

包含所需的信息。 构建架构:

   public static void ConstructSchema(FileInfo theFile)
    {
        StringBuilder schema = new StringBuilder(); 
        DataTable data = LoadCSV(theFile); 
        schema.AppendLine("[" + theFile.Name + "]");
        schema.AppendLine("ColNameHeader=True"); 
        for (int i = 0; i < data.Columns.Count; i++)
        {
            schema.AppendLine("col" + (i + 1).ToString() + "=" + data.Columns[i].ColumnName + " Text");
        }   
        string schemaFileName = theFile.DirectoryName + @"\Schema.ini";
        TextWriter tw = new StreamWriter(schemaFileName);   
        tw.WriteLine(schema.ToString());
        tw.Close();  
    }

加载csv作为数据表

public static DataTable LoadCSV(FileInfo theFile)
    {   
        string sqlString = "Select * FROM [" + theFile.Name + "];";
        string conStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source="
            + theFile.DirectoryName + ";" + "Extended Properties='text;HDR=YES;'";
        DataTable theCSV = new DataTable();

        using (OleDbConnection conn = new OleDbConnection(conStr))
        {
            using (OleDbCommand comm = new OleDbCommand(sqlString, conn))
            {
                using (OleDbDataAdapter adapter = new OleDbDataAdapter(comm))
                {
                    adapter.Fill(theCSV);
                }
            }
        }
        return theCSV;
    }

转换成xml

 public static XElement GetXMLFromCSV(FileInfo theFile, string rootNodeName, string itemName)
    {
        XElement retVal;
        DataTable data;
        data = CrateCsvAndSchema(theFile); 
        DataSet ds = new DataSet(rootNodeName);
        data.TableName = itemName;
        ds.Tables.Add(data); 
        retVal = XElement.Parse(ds.GetXml());  
        return retVal;
    }

关于c# - 将 csv 加载到 oleDB 中并将所有推断的数据类型强制为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1688497/

相关文章:

c# - 获取特定 ActiveDirectoryGroup 的所有用户的列表

c# - 如何使用 dotnetzip 检查文件是否存在于 zip 文件中

php - 在 PHP 中读取 CSV 并按数组值输出其内容

email - Magento 使用 CSV 发送帖子

vb.net - 在 VB.net 2005 中打开 FoxPro 表

ms-access - VBScript 和 Access MDB - 800A0E7A - "Provider cannot be found. It may not be properly installed"

c# - ALL_UPPER 常量的 ReSharper Intellisense

c# - 在某些情况下,OptimisticConcurrencyException 在 Entity Framework 中不起作用

python - 为有效数据帧添加值并忽略无效解析

sql-server-2005 - 不支持 ITransactionLocal 接口(interface)