Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Manually Add Header in CsvHelper.CsvWriter

Tags:

c#

csvhelper

I'm using CsvHelper class to write rows in DataTable to a csv file. The code works but I can't get it to write the headers.

How can I add the headers manually without creating a Class Map?

http://joshclose.github.io/CsvHelper/

DataTable dt = GetDataTableFromDB();

System.IO.MemoryStream memoryStream = new System.IO.MemoryStream();
System.IO.StreamWriter streamWriter = new System.IO.StreamWriter( memoryStream );
CsvHelper.CsvWriter writer = new CsvHelper.CsvWriter( streamWriter );

foreach ( DataColumn column in properties.Columns )
    writer.WriteHeader( column.ColumnName );    //<--- How do I write to column

foreach ( DataRow row in dt.Rows )
{
    foreach ( object item in row.ItemArray )
        writer.WriteField( item.ToString() );

    writer.NextRecord();
}
like image 377
Kathy Judd Avatar asked Sep 07 '15 17:09

Kathy Judd


1 Answers

Update:

DataTable functionality is built in now. https://joshclose.github.io/CsvHelper/examples/data-table

Original:

This is actually in the documentation under Writing to a CSV using a DataTable.

I'll put the code example here too.

using( var dt = new DataTable() )
{
    dt.Load( dataReader );
    foreach( DataColumn column in dt.Columns )
    {
        csv.WriteField( column.ColumnName );
    }
    csv.NextRecord();

    foreach( DataRow row in dt.Rows )
    {
        for( var i = 0; i < dt.Columns.Count; i++ )
        {
            csv.WriteField( row[i] );
        }
        csv.NextRecord();
    }
}

Headers aren't anything special or different in a CSV file.

like image 50
Josh Close Avatar answered Oct 12 '22 23:10

Josh Close