Export to CSV using MVC, C# and jQuery

后端 未结 9 1028
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-12 13:42

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 m

相关标签:
9条回答
  • 2020-12-12 14:04

    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();
    
    0 讨论(0)
  • 2020-12-12 14:06

    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");
        }
    
    0 讨论(0)
  • 2020-12-12 14:11

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

    $('#btn_export').click(function () {
        window.location.href = 'NewsLetter/Export';
    });
    
    0 讨论(0)
提交回复
热议问题