Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
394 views
in Technique[技术] by (71.8m points)

export data from CSV to datatable in c#

I am using below code to export data from a csv file to datatable. As the values are of mixed text i.e. both numbers and Alphabets, some of the columns are not getting exported to Datatable.

I have done some research here and found that we need to set ImportMixedType = Text and TypeGuessRows = 0 in registry which even did not solve the problem. Below code is working for some files even with mixed text.

Could someone tell me what is wrong with below code. Do I miss some thing here.

if (isFirstRowHeader)
{
    header = "Yes";
}

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))
        {                           
            adapter.Fill(table);
        }
        connection.Close();
     }
 }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The main thing that would probably help is to first stop using OleDB objects for reading a delimited file. I suggest using the 'TextFieldParser' which is what I have successfully used for over 2 years now for a client.

http://www.dotnetperls.com/textfieldparser

There may be other issues, but without seeing your .CSV file, I can't tell you where your problem may lie.

The TextFieldParser is specifically designed to parse comma delimited files. The OleDb objects are not. So, start there and then we can determine what the problem may be, if it persists.

If you look at an example on the link I provided, they are merely writing lines to the console. You can alter this code portion to add rows to a DataTable object, as I do, for sorting purposes.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...