How to read a CSV file into a .NET Datatable

后端 未结 22 2112
野性不改
野性不改 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:56

    Hey its working 100%

      public static DataTable ConvertCSVtoDataTable(string strFilePath)
      {
        DataTable dt = new DataTable();
        using (StreamReader sr = new StreamReader(strFilePath))
        {
            string[] headers = sr.ReadLine().Split(',');
            foreach (string header in headers)
            {
                dt.Columns.Add(header);
            }
            while (!sr.EndOfStream)
            {
                string[] rows = sr.ReadLine().Split(',');
                DataRow dr = dt.NewRow();
                for (int i = 0; i < headers.Length; i++)
                {
                    dr[i] = rows[i];
                }
                dt.Rows.Add(dr);
            }
    
        }
    
    
        return dt;
       }
    

    CSV Image enter image description here

    Data table Imported enter image description here

提交回复
热议问题