How to read a CSV file into a .NET Datatable

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

    Just sharing this extension methods, I hope that it can help someone.

    public static List ToCSV(this DataSet ds, char separator = '|')
    {
        List lResult = new List();
    
        foreach (DataTable dt in ds.Tables)
        {
            StringBuilder sb = new StringBuilder();
            IEnumerable columnNames = dt.Columns.Cast().
                                              Select(column => column.ColumnName);
            sb.AppendLine(string.Join(separator.ToString(), columnNames));
    
            foreach (DataRow row in dt.Rows)
            {
                IEnumerable fields = row.ItemArray.Select(field =>
                  string.Concat("\"", field.ToString().Replace("\"", "\"\""), "\""));
                sb.AppendLine(string.Join(separator.ToString(), fields));
            }
    
            lResult.Add(sb.ToString());
        }
        return lResult;
    }
    
    public static DataSet CSVtoDataSet(this List collectionCSV, char separator = '|')
    {
        var ds = new DataSet();
    
        foreach (var csv in collectionCSV)
        {
            var dt = new DataTable();
    
            var readHeader = false;
            foreach (var line in csv.Split(new[] { Environment.NewLine }, StringSplitOptions.None))
            {
                if (!readHeader)
                {
                    foreach (var c in line.Split(separator))
                        dt.Columns.Add(c);
                }
                else
                {
                    dt.Rows.Add(line.Split(separator));
                }
            }
    
            ds.Tables.Add(dt);
        }
    
        return ds;
    }
    

提交回复
热议问题