Export to CSV using MVC, C # and jQuery

I am trying to export a list to a CSV file. I brought everything to the point that I want to write the file to the response stream. It does nothing.

Here is my code:

Call 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 happens. Is it possible to save the file this way?

respectfully

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

 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 seems good to me ..

Edit
I got rid of the jQuery part that replaced it with a hyperlink, and now this works fine for me:

 <a class="export" href="NewsLetter/Export">exporteren</a> 
+72
jquery c # asp.net-mvc csv
Jan 12 '11 at 12:40
source share
9 answers

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

  public FileContentResult DownloadCSV() { string csv = "Charlie, Chaplin, Chuckles"; return File(new System.Text.UTF8Encoding().GetBytes(csv), "text/csv", "Report123.csv"); } 
+205
Feb 03 2018-11-11T00:
source share

With MVC, you can simply return the file as follows:

 public ActionResult ExportData() { System.IO.FileInfo exportFile = //create your ExportFile return File(exportFile.FullName, "text/csv", string.Format("Export-{0}.csv", DateTime.Now.ToString("yyyyMMdd-HHmmss"))); } 
+11
Jan 12 '11 at 13:27
source share

In addition to Biff MaGriff answer. To export a file using jQuery, redirect the user to a new page.

 $('#btn_export').click(function () { window.location.href = 'NewsLetter/Export'; }); 
+6
Oct 12 '13 at 9:06 on
source share

What happens if you get rid of the stringwriter:

  Response.Clear(); Response.AddHeader("Content-Disposition", "attachment; filename=adressenbestand.csv"); Response.ContentType = "text/csv"; //write the header Response.Write(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)) { Response.Write(String.Format("{0},{1},{2},{3}", record.EmailAddress, record.Gender.HasValue ? resourceManager.GetString(record.Gender.ToString()) : "", record.FirstName, record.LastName)); } Response.End(); 
+4
Jan 12 '11 at
source share

Respect for Biff, here are a few settings that let me use the method to bounce CSV from jQuery / Post to the server and return as a CSV invitation to the user.

  [Themed(false)] public FileContentResult DownloadCSV() { var csvStringData = new StreamReader(Request.InputStream).ReadToEnd(); csvStringData = Uri.UnescapeDataString(csvStringData.Replace("mydata=", "")); return File(new System.Text.UTF8Encoding().GetBytes(csvStringData), "text/csv", "report.csv"); } 

You will need an unescape line if you click this on a form with code like this:

  var input = $("<input>").attr("type", "hidden").attr("name", "mydata").val(data); $('#downloadForm').append($(input)); $("#downloadForm").submit(); 
+3
Mar 17 '13 at 15:10
source share

Even if you solved the problem, try exporting csv using mvc.

 return new FileStreamResult(fileStream, "text/csv") { FileDownloadName = fileDownloadName }; 
+1
Oct 08 '12 at 11:56
source share

Use the button to select .click (call the java script). From there, calling the controller method using window.location.href = 'Controller / Method';

In the controller, either a database call, or data acquisition or a method call, receives data from a database table in a datatable, and then perform the following actions:

 using (DataTable dt = new DataTable()) { sda.Fill(dt); //Build the CSV file data as a Comma separated string. string csv = string.Empty; foreach (DataColumn column in dt.Columns) { //Add the Header row for CSV file. csv += column.ColumnName + ','; } //Add new line. csv += "\r\n"; foreach (DataRow row in dt.Rows) { foreach (DataColumn column in dt.Columns) { //Add the Data rows. csv += row[column.ColumnName].ToString().Replace(",", ";") + ','; } //Add new line. csv += "\r\n"; } //Download the CSV file. Response.Clear(); Response.Buffer = true; Response.AddHeader("content-disposition", "attachment;filename=SqlExport"+DateTime.Now+".csv"); Response.Charset = ""; //Response.ContentType = "application/text"; Response.ContentType = "application/x-msexcel"; Response.Output.Write(csv); Response.Flush(); Response.End(); } 
+1
Sep 01 '17 at 6:19 on 06:19
source share

I think you forgot to use

  Response.Flush(); 

under

  Response.Write(sw); 

check

0
Jul 21 '16 at 6:50
source share

A simple excel file is created in mvc 4

public results ActionResult () {return file (new System.Text.UTF8Encoding (). GetBytes ("string data"), "application / csv", "filename.csv"); }

-2
Apr 04 '17 at 9:53 on
source share



All Articles