使用MVC,C#和jQuery导出为CSV [英] Export to CSV using MVC, C# and jQuery
本文介绍了使用MVC,C#和jQuery导出为CSV的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试将列表导出到CSV文件. 我完成了所有工作,直到我想将文件写入响应流.这什么也没做.
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.
这是我的代码:
从页面调用方法.
$('#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)
之后什么也没有发生.甚至可以用这种方式保存文件吗?
But after Response.Write(sw)
nothing is happening. Is it even possible to save a file this way?
致谢
修改
单击按钮时看到的响应标题为:
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
对我来说似乎还可以.
修改
我摆脱了jQuery部分,用超链接代替了它,现在对我来说很好用:
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>
推荐答案
yan.kun步入正轨,但这要容易得多.
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");
}
这篇关于使用MVC,C#和jQuery导出为CSV的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文