How to read a CSV file into a .NET Datatable

后端 未结 22 2408
野性不改
野性不改 2020-11-22 05:12

How can I load a CSV file into a System.Data.DataTable, creating the datatable based on the CSV file?

Does the regular ADO.net functionality allow this?

22条回答
  •  醉梦人生
    2020-11-22 05:57

    For those of you wishing not to use an external library, and prefer not to use OleDB, see the example below. Everything I found was either OleDB, external library, or simply splitting based on a comma! For my case OleDB was not working so I wanted something different.

    I found an article by MarkJ that referenced the Microsoft.VisualBasic.FileIO.TextFieldParser method as seen here. The article is written in VB and doesn't return a datatable, so see my example below.

    public static DataTable LoadCSV(string path, bool hasHeader)
        {
            DataTable dt = new DataTable();
    
            using (var MyReader = new Microsoft.VisualBasic.FileIO.TextFieldParser(path))
            {
                MyReader.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.Delimited;
                MyReader.Delimiters = new String[] { "," };
    
                string[] currentRow;
    
                //'Loop through all of the fields in the file.  
                //'If any lines are corrupt, report an error and continue parsing.  
                bool firstRow = true;
                while (!MyReader.EndOfData)
                {
                    try
                    {
                        currentRow = MyReader.ReadFields();
    
                        //Add the header columns
                        if (hasHeader && firstRow)
                        {
                            foreach (string c in currentRow)
                            {
                                dt.Columns.Add(c, typeof(string));
                            }
    
                            firstRow = false;
                            continue;
                        }
    
                        //Create a new row
                        DataRow dr = dt.NewRow();
                        dt.Rows.Add(dr);
    
                        //Loop thru the current line and fill the data out
                        for(int c = 0; c < currentRow.Count(); c++)
                        {
                            dr[c] = currentRow[c];
                        }
                    }
                    catch (Microsoft.VisualBasic.FileIO.MalformedLineException ex)
                    {
                        //Handle the exception here
                    }
                }
            }
    
            return dt;
        }
    

提交回复
热议问题