Search code examples
c#csvhelper

Write Header Record to CSV File


I'm using CSVHelper to write a DataReader result to a csv file and everything works great except that I need my header names to be manually entered instead of just pulling the column name from the datareader.

So currently I use the following to get my data and place a header: It comes right from the documentation of CSVHelper: http://joshclose.github.io/CsvHelper/#misc-faq

            while (rdr.Read())
            {
                if (!hasHeaderBeenWritten)
                {
                    for (var i = 0; i < rdr.FieldCount; i++)
                    {
                        csv.WriteField(rdr.GetName(i));
                    }
                    csv.NextRecord();
                    hasHeaderBeenWritten = true;

                    foreach (var item in dataList)
                    {
                        csv.WriteRecord(item);
                    }
                }
                for (var i = 0; i < rdr.FieldCount; i++)
                {
                    csv.WriteField(rdr[i]);
                }
                csv.NextRecord();
            }

I'm looking basically to add a manual name to the 3 columns that my class is allow it to return vs the rdr.GetName(i) method that is being used above.

Does anyone have any solutions? I've tried doing a csv.WriteField("namehere"[i]); which obviously didn't work and instead spanned each letter out across the three columns and then stopped.


Solution

  • Question: "HOW DO I PROPERLY ADD A CUSTOM HEADER IN CSVHELPER?"

    Simply create an string array with the column names you wish and pass them in using csv.WriteField(*ARRAYHERE*)[i]; and for each column a they will be added in order they appear in the array.

    Create they array:

    string[] arrayHeader = new string[] { "Header1", "Header2", "Header3" };
    

    Pass each column name in:

                        for (var i = 0; i < rdr.FieldCount; i++)
                        {
                            //csv.WriteField(rdr.GetName(i));
                            csv.WriteField(arrayHeader[i]);
                        }