Manually Add Header in CsvHelper.CsvWriter

后端 未结 2 848
终归单人心
终归单人心 2021-02-13 06:58

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

相关标签:
2条回答
  • 2021-02-13 07:03

    The easiest way is to use

    writer.WriteHeader<YourClass>();
    

    More complete example:

    using (StreamWriter sw = new StreamWriter(@"C:\output.csv"))
    {
      using (CsvWriter writer = new CsvWriter(sw))
      {
         writer.WriteHeader<YourClass>();
    
         writer.WriteRecord(yourRecordVariable);
      }
    }
    

    As was posted here on Google groups by the author Josh Close.

    0 讨论(0)
  • 2021-02-13 07:27

    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.

    0 讨论(0)
提交回复
热议问题