How to read a CSV file into a .NET Datatable

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

    Modified from Mr ChuckBevitt

    Working solution:

    string CSVFilePathName = APP_PATH + "Facilities.csv";
    string[] Lines = File.ReadAllLines(CSVFilePathName);
    string[] Fields;
    Fields = Lines[0].Split(new char[] { ',' });
    int Cols = Fields.GetLength(0);
    DataTable dt = new DataTable();
    //1st row must be column names; force lower case to ensure matching later on.
    for (int i = 0; i < Cols-1; i++)
            dt.Columns.Add(Fields[i].ToLower(), typeof(string));
    DataRow Row;
    for (int i = 0; i < Lines.GetLength(0)-1; i++)
    {
            Fields = Lines[i].Split(new char[] { ',' });
            Row = dt.NewRow();
            for (int f = 0; f < Cols-1; f++)
                    Row[f] = Fields[f];
            dt.Rows.Add(Row);
    }
    

提交回复
热议问题