How to add CsvHelper records to DataTable to use for SqlBulkCopy to the database

后端 未结 4 1277
旧时难觅i
旧时难觅i 2021-02-14 08:40

I am trying to read a CSV file with CsvHelper, load each record into a DataTable, and then use SqlBulkCopy to insert the data into a database table. With the current code, I get

4条回答
  •  滥情空心
    2021-02-14 09:12

    Josh added support to read headers last year and the following block may be useful to those who just want to build a DataTable using the schema of the CSV document. I wanted to post this as a comment to Josh's answer as it is only a small modification but posting as an answer as I couldn't format a code block in Comments.

        private DataTable BuildDataTable()
        {
            var dt = new DataTable();
    
            using (var textReader = new StreamReader(_path))
            {
                using (var csv = new CsvReader(textReader))
                {
                    csv.ReadHeader();
                    foreach (var header in csv.FieldHeaders)
                    {
                        dt.Columns.Add(header);
                    }
    
    
                    while (csv.Read())
                    {
                        var row = dt.NewRow();
                        foreach (DataColumn column in dt.Columns)
                        {
                            row[column.ColumnName] = csv.GetField(column.DataType, column.ColumnName);
                        }
                        dt.Rows.Add(row);
                    }
                }
            }
    
            return dt;
        }
    

提交回复
热议问题