Search code examples
export-to-csvcsvhelper

How to create csv file in Download/Stream functionality using CsvHelper in asp.net web forms


I am using below code on Button Click event. Along with data , web page html is getting into csv file.

enter image description here

var data = new[]
            {
                new Project { CustomerName = "Big Corp", Title = "CRM updates", Deadline = DateTime.Today.AddDays(-2) },
                new Project { CustomerName = "Imaginary Corp", Title = "Sales system", Deadline = DateTime.Today.AddDays(1) }
            };

        Response.ClearContent();
        Response.ContentType = "application/csv";
        Response.AddHeader("content-disposition", @"attachment;filename=""export.csv""");
        
        var preamble = Encoding.UTF8.GetPreamble();

        Response.OutputStream.Write(preamble, 0, preamble.Length);



        using (var writer = new StreamWriter(Response.OutputStream))
        using (var csvWriter = new CsvWriter(writer, System.Globalization.CultureInfo.CurrentCulture))
        {
            //csvWriter.Configuration.Delimiter = Environment.NewLine;
            csvWriter.Configuration.HasHeaderRecord = true;
            csvWriter.Configuration.AutoMap<Project>();

            //csvWriter.WriteHeader<Project>();
            //csvWriter.WriteRecords(data);

            csvWriter.Configuration.Delimiter = ",";

            csvWriter.WriteField("CustomerName");
            csvWriter.WriteField("Title");
            csvWriter.WriteField("Deadline");
            csvWriter.NextRecord();

            foreach (var project in data)
            {

                csvWriter.WriteField(project.CustomerName);
                csvWriter.WriteField(project.Title);
                csvWriter.WriteField(project.Deadline);
                csvWriter.WriteField(Environment.NewLine);
                csvWriter.NextRecord();
            }
            csvWriter.Flush();
            writer.Flush();
        }

Solution

  • Try adding Response.End();

    using (var writer = new StreamWriter(Response.OutputStream))
    using (var csvWriter = new CsvWriter(writer, System.Globalization.CultureInfo.CurrentCulture))
    {
        csvWriter.Configuration.HasHeaderRecord = true; // Only used with WriteRecords(), defaults to true.
        csvWriter.Configuration.AutoMap<Project>();  // This is used to create a ClassMap.  CsvWriter will use AutoMap if no map is passed to it.
    
        csvWriter.Configuration.Delimiter = ",";
    
        csvWriter.WriteField("CustomerName");
        csvWriter.WriteField("Title");
        csvWriter.WriteField("Deadline");
        csvWriter.NextRecord();
    
        foreach (var project in data)
        {
    
            csvWriter.WriteField(project.CustomerName);
            csvWriter.WriteField(project.Title);
            csvWriter.WriteField(project.Deadline);
            csvWriter.WriteField(Environment.NewLine); // Not necessary. NextRecord() adds a newline. This will add a newline as a field in quotes.
            csvWriter.NextRecord();
        }
        csvWriter.Flush();  // You almost never want to use this. Mostly used by the backend code.  NextRecord calls Flush() to serialize the row to the TextWriter.
        writer.Flush();  // The using statement will do this for you.
    }
    Response.End();
    

    You could make it a lot easier on yourself and just use WriteRecords(). The only configuration that is necessary is csvWriter.Configuration.Delimiter = ","; if CurrentCulture uses a different delimiter. Otherwise all the other configurations you added are the default configurations.

    using (var writer = new StreamWriter(Response.OutputStream))
    using (var csvWriter = new CsvWriter(writer, System.Globalization.CultureInfo.CurrentCulture))
    {
        csvWriter.Configuration.Delimiter = ",";
                    
        csvWriter.WriteRecords(data);
    }
    Response.End();