Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Export to CSV using MVC, C# and jQuery

I am trying to export a list to a CSV file. I got it all working up to the point I want to write to file to the response stream. This doesn't do anything.

Here is my code:

Call the the method from the page.

$('#btn_export').click(function () {          $.post('NewsLetter/Export'); }); 

The code in the controller is as follows:

[HttpPost]         public void Export()         {             try             {                 var filter = Session[FilterSessionKey] != null ? Session[FilterSessionKey] as SubscriberFilter : new SubscriberFilter();                  var predicate = _subscriberService.BuildPredicate(filter);                 var compiledPredicate = predicate.Compile();                 var filterRecords = _subscriberService.GetSubscribersInGroup().Where(x => !x.IsDeleted).AsEnumerable().Where(compiledPredicate).GroupBy(s => s.Subscriber.EmailAddress).OrderBy(x => x.Key);                  ExportAsCSV(filterRecords);             }             catch (Exception exception)             {                 Logger.WriteLog(LogLevel.Error, exception);             }         }          private void ExportAsCSV(IEnumerable<IGrouping<String, SubscriberInGroup>> filterRecords)         {             var sw = new StringWriter();             //write the header             sw.WriteLine(String.Format("{0},{1},{2},{3}", CMSMessages.EmailAddress, CMSMessages.Gender, CMSMessages.FirstName, CMSMessages.LastName));              //write every subscriber to the file             var resourceManager = new ResourceManager(typeof(CMSMessages));             foreach (var record in filterRecords.Select(x => x.First().Subscriber))             {                 sw.WriteLine(String.Format("{0},{1},{2},{3}", record.EmailAddress, record.Gender.HasValue ? resourceManager.GetString(record.Gender.ToString()) : "", record.FirstName, record.LastName));             }              Response.Clear();             Response.AddHeader("Content-Disposition", "attachment; filename=adressenbestand.csv");             Response.ContentType = "text/csv";             Response.Write(sw);             Response.End();         } 

But after Response.Write(sw) nothing is happening. Is it even possible to save a file this way?

Regards

Edit
The response headers I see when I click the button are:

HTTP/1.1 200 OK Cache-Control: private Content-Type: text/csv; charset=utf-8 Server: Microsoft-IIS/7.5 X-AspNetMvc-Version: 2.0 Content-Disposition: attachment; filename=adressenbestand.csv X-Powered-By: ASP.NET Date: Wed, 12 Jan 2011 13:05:42 GMT Content-Length: 113 

Which seem OK to me..

Edit
I got rid of the jQuery part en replaced it by an hyperlink and this is working fine for me now:

<a class="export" href="NewsLetter/Export">exporteren</a> 
like image 418
Gerard Avatar asked Jan 12 '11 12:01

Gerard


People also ask

How do I export a csv file in MVC?

When the Export Button is clicked, the data from Database is fetched using Entity Framework and a Comma Separated (Delimited) string is generated which is exported and downloaded as CSV file in ASP.Net MVC Razor. Here I am making use of Microsoft's Northwind Database. You can download it from here.

How do I import a CSV file into .NET core?

First of All, we have to install this NuGet package into our project. Our CSV file looks like this, and we have encircled our header row. Now we will create a class with the same properties as we have a header row in the CSV file because we have to receive data accurately from the CSV file.


1 Answers

yan.kun was on the right track but this is much much easier.

    public FileContentResult DownloadCSV()     {         string csv = "Charlie, Chaplin, Chuckles";         return File(new System.Text.UTF8Encoding().GetBytes(csv), "text/csv", "Report123.csv");     } 
like image 167
Biff MaGriff Avatar answered Oct 19 '22 10:10

Biff MaGriff