使用MVC,C#和jQuery导出为CSV

我正在尝试将列表导出到CSV文件。 我已经完成了所有工作,直到我想写入文件到响应stream。 这没有做任何事情。

这是我的代码:

从页面调用该方法。

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

控制器中的代码如下所示:

 [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(); } 

但是在Response.Write(sw)没有任何事情发生。 这样可以保存文件吗?

问候

编辑
我点击button时看到的响应标题是:

 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 

这对我来说似乎可以

编辑
我摆脱了jQuery的一部分,取而代之的是一个超链接,这现在对我来说很好:

 <a class="export" href="NewsLetter/Export">exporteren</a> 

yan.kun在正确的轨道上,但是这要容易得多。

  public FileContentResult DownloadCSV() { string csv = "Charlie, Chaplin, Chuckles"; return File(new System.Text.UTF8Encoding().GetBytes(csv), "text/csv", "Report123.csv"); } 

有了MVC,你可以简单地返回一个像这样的文件:

 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"))); } 

除了比夫·马格里夫的回答。 要使用JQuery导出文件,请将用户redirect到新页面。

 $('#btn_export').click(function () { window.location.href = 'NewsLetter/Export'; }); 

如果你摆脱了string作者,会发生什么:

  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(); 

尊重比夫,这里有一些调整,让我使用该方法从jQuery / PostpopupCSV反对服务器,并作为CSV提示回来的用户。

  [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"); } 

如果你使用下面这样的代码从一个表单中打开,你将需要unescape行,

  var input = $("<input>").attr("type", "hidden").attr("name", "mydata").val(data); $('#downloadForm').append($(input)); $("#downloadForm").submit(); 

即使你已经解决了你的问题,这里是另外一个尝试使用mvc导出csv。

 return new FileStreamResult(fileStream, "text/csv") { FileDownloadName = fileDownloadName }; 

从一个button中查看call .click(调用一些java脚本)。 从那里调用控制器方法window.location.href ='Controller / Method';

在控制器中,执行数据库调用并获取数据表或调用某个方法从数据表中获取数据到数据表,然后执行以下操作,

 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(); } 

我想你已经忘记使用了

  Response.Flush(); 

  Response.Write(sw); 

请检查

简单的excel文件在mvc 4中创build

public ActionResult results(){return File(new System.Text.UTF8Encoding()。GetBytes(“string data”),“application / csv”,“filename.csv”); }