简体   繁体   English

C#使用OleDb导入CSV

[英]C# Importing CSV using OleDb

I'm trying to set up code to import .CSV files into .NET. 我正在尝试设置代码以将.CSV文件导入.NET。

I've tried both Microsoft.Jet.OLEDB.4.0 and Microsoft.ACE.OLEDB.12.0 providers, including modifying the Extended Properties and even modifying corresponding registry keys for each. 我已经尝试使用Microsoft.Jet.OLEDB.4.0Microsoft.ACE.OLEDB.12.0提供程序,包括修改Extended Properties ,甚至为每个修改相应的注册表项。 I have yet to come up with a solution for what I am attempting to do: 我还没有想出一个解决方案:

I would like to import each field as text, but leave fields longer than 255 characters un-truncated. 我想将每个字段导入为文本,但保留长度不超过255个字符的字段。

What I've found so far is that I can have one or the other, but not both. 到目前为止,我发现我可以拥有一个或另一个,但不能同时拥有两个。

  • If I set the ImportMixedTypes registry value to Majority Type , it leaves 255+ character text fields un-truncated, but converts other fields to unwanted types. 如果我将ImportMixedTypes注册表值设置为Majority Type ,它将保留255个以上的字符文本字段不被截断,但是将其他字段转换为不需要的类型。
  • If I set the ImportMixedTypes registry value to Text , it truncates 255+ character text fields, but leaves the other field types as text. 如果将ImportMixedTypes注册表值设置为Text ,它将截断255个以上的字符文本字段,但将其他字段类型保留为文本。

How do I accomplish this using OleDb? 如何使用OleDb完成此操作?


Additional info: 附加信息:

I have a "notes" column, which can contain very lengthy text. 我有一个“注释”列,其中可以包含很长的文本。 I also have a "zip code" column, which contains mixed zip-code formats (5-digit and 9-digit with a dash). 我也有一个“邮政编码”列,其中包含混合的邮政编码格式(5位和9位带破折号)。 Typically, the 5-digit zip-code format is more popular, so the importer thinks that the column should be integer type, leaving the 9-digit zip-codes as null values after import. 通常,5位数的邮政编码格式更受欢迎,因此导入程序认为该列应为整数类型,导入后将9位数的邮政编码保留为空值。

Have you considered using something as versatile as the FileHelpers library ( http://filehelpers.sourceforge.net/ ) instead? 您是否考虑过使用像FileHelpers库( http://filehelpers.sourceforge.net/ )一样通用的工具?

Or alternatively if your requirements are no more than you state (read csv file, get string fields), use something really simple such as: 或者,如果您的要求仅满足您的要求(读取csv文件,获取字符串字段),请使用非常简单的方法,例如:

public static class SimpleCsvImport
{
    public static IEnumerable<List<string>> Import(string csvFileName)
    {
        using (var reader = File.OpenText(csvFileName))
        {
            while (!reader.EndOfStream)
            {
                var fields = reader.ReadLine().Split(new[] { ',' }, StringSplitOptions.None).Select(f => f.Trim()).ToList();
                if (fields.Count > 0)
                    yield return fields;
            }
        }
    }
}

i have implemented this code to read memo field (Microsoft Access): 我已实现以下代码以读取备注字段(Microsoft Access):

  private string GetMemoField(string TableName, string FieldName, string IdentityFieldName, string IdentityFieldValue, OleDbConnection conn)
    {
        string ret = "";

        OleDbCommand cmd1 = new OleDbCommand("SELECT " + FieldName + " FROM “ + TableName + “ WHERE " + IdentityFieldName + "=" + IdentityFieldValue, conn);

                var reader = cmd1.ExecuteReader(System.Data.CommandBehavior.SequentialAccess);  // Create the DataReader that will get the memo field one buffer at a time

        if (reader.Read())
        {
            long numberOfChars = reader.GetChars(/*Field pos*/ 0, 0, null, 0, 0);   // Total number of memo field's chars

            if (numberOfChars > 0)
            {
                int bufferSize = 1024;
                char[] totalBuffer = new char[64*bufferSize];    // Array to hold memo field content

                long dataIndex = 0;

                do
                {

                    char[] buffer = new char[bufferSize];   // Buffer to hold single read
                    long numberOfCharsReaded = reader.GetChars(0, dataIndex, buffer, 0, bufferSize);

                    if (numberOfCharsReaded == 0)
                    {
                        ret = new string(totalBuffer,0, (int)numberOfChars);
                        break;
                    }

                    Array.Copy(buffer, 0, totalBuffer, dataIndex, numberOfCharsReaded);     // Add temporary buffer to main buffer
                    dataIndex += numberOfCharsReaded;

                } while (true);
            }
        }

        return ret;
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM