Search code examples
c#linqtocsv

How to create csv with header and footer using LinqtoCsv or anything better in C#


I am trying to export data in csv format. I am using LinqToCsv to create csv. Is it possible to create footer section using LinqToCsv?

Can anyone help me how to create a csv with header and footer using LinqToCsv or with anything else using C#?

I need something to create csv of following format:

Column 1|Column 2|Column 3|Column 4|Column 5
--- data goes here
---
Trailer: test | 1231312 | xxx

Thanks


Solution

  • I'm using CsvHelper for this example.

    class TempRecord
    {
        public string FirstCol { get; set; }
        public string LastCol { get; set; }
    }
    class FooterRecord
    {
        public string FooterText { get; set; }        
    }
    class Program
    {
        static void Main(string[] args)
        {
            var tempRecords = new List<TempRecord>();
            tempRecords.Add(new TempRecord{FirstCol = "row1a", LastCol="row1z"});
            tempRecords.Add(new TempRecord{FirstCol = "row2a", LastCol="row2z"});
    
            var outputCsv = @"M:\temp\temp.csv";            
            using (TextWriter writer = File.AppendText(outputCsv))
            {
                var csv = new CsvWriter(writer);
                csv.Configuration.HasHeaderRecord = true;
                csv.WriteRecords(tempRecords);
                csv.WriteRecord(new FooterRecord { FooterText = "Hey! THis is a footer" });
            }
    
        }
    }
    

    Here's the output csv file:

    enter image description here