使用 MVC、C# 和 jQuery 导出到 CSV
我正在尝试将列表导出到 CSV 文件。 我已经完成了所有工作,直到我想将文件写入响应流。这没有任何作用。
这是我的代码:
从页面调用该方法。
$('#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)
之后什么也没有发生。是否可以通过这种方式保存文件?
问候
编辑
单击按钮时我看到的响应标头是:
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>
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>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
yan.kun 走在正确的轨道上,但这要容易得多。
yan.kun was on the right track but this is much much easier.
使用 MVC,您可以简单地返回如下文件:
With MVC you can simply return a file like this:
除了 Biff MaGriff 的回答。要使用 JQuery 导出文件,请将用户重定向到新页面。
In addition to Biff MaGriff's answer. To export the file using JQuery, redirect the user to a new page.
如果去掉字符串编写器会发生什么:
What happens if you get rid of the stringwriter:
尊敬的 Biff,这里有一些调整,让我可以使用该方法从 jQuery/Post 向服务器弹回 CSV,并作为 CSV 提示返回给用户。
如果您从具有如下代码的表单中点击此行,则需要 unescape 行,
Respect to Biff, here's a few tweaks that let me use the method to bounce CSV from jQuery/Post against the server and come back as a CSV prompt to the user.
You'll need the unescape line if you are hitting this from a form with code like the following,
从视图中的按钮调用 .click(调用一些 java 脚本)。从那里通过 window.location.href = 'Controller/Method' 调用控制器方法;
在控制器中,要么执行数据库调用并获取数据表,要么调用某种方法将数据从数据库表获取到数据表,然后执行以下操作,
From a button in view call .click(call some java script). From there call controller method by window.location.href = 'Controller/Method';
In controller either do the database call and get the datatable or call some method get the data from database table to a datatable and then do following,
即使您已经解决了问题,这里还有另一种尝试使用 mvc 导出 csv。
Even if you have resolved your issue, here is another one try to export csv using mvc.
我认为您忘记使用
下面的内容
,请检查
I Think you have forgot to use
under
please check