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

Ger*_*ard 81 c# csv asp.net-mvc jquery

我正在尝试将列表导出为CSV文件.我完成了所有工作,我想写入文件到响应流.这没有任何作用.

这是我的代码:

从页面调用方法.

$('#btn_export').click(function () {
         $.post('NewsLetter/Export');
});
Run Code Online (Sandbox Code Playgroud)

控制器中的代码如下:

[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();
        }
Run Code Online (Sandbox Code Playgroud)

但是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
Run Code Online (Sandbox Code Playgroud)

这似乎对我来说..

编辑
我摆脱了jQuery部分用超链接替换它,这对我现在工作正常:

<a class="export" href="NewsLetter/Export">exporteren</a>
Run Code Online (Sandbox Code Playgroud)

Bif*_*iff 237

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

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


yan*_*kun 12

使用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")));
}
Run Code Online (Sandbox Code Playgroud)

  • 你真的想在网络服务器上创建一堆文件吗?清理它们怎么样?安全性怎么样? (8认同)

Har*_*der 7

除了Biff MaGriff的回答.要使用JQuery导出文件,请将用户重定向到新页面.

$('#btn_export').click(function () {
    window.location.href = 'NewsLetter/Export';
});
Run Code Online (Sandbox Code Playgroud)


chr*_*ris 5

如果您放弃了字符串编写器,将会发生什么:

        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();
Run Code Online (Sandbox Code Playgroud)