How to Export CSV file from ASP.NET core
Consider changing approach to align more with current suggested syntax.
Construct the CSV and return a FileResult, which allows the code to not have to directly manipulate the Response
object.
[HttpGet]
public IActionResult MyExportAction() {
var progresses = _elearnContext.Progress.Where(p => p.UserId == id)
.Include(p => p.User.UserMetaData)
.Include(p => p.Quiz)
.Include(p => p.User.Groups)
.OrderByDescending(p => p.UpdatedAt)
.ToList()
.Select(progress =>
new ReportCSVModel() {
Quiz = progress.Quiz.Title,
Score = (progress.CorrectAnswersCount * progress.PointsPerQuestion).ToString(),
Status = progress.Status,
CompletedDate = progress.UpdatedAt.ToString(),
Location = progress.User.UserMetaData != null ? progress.User.UserMetaData.Location : "",
Group = progress.User.Groups.FirstOrDefault() != null ? progress.User.Groups.FirstOrDefault().Name : ""
}
);
List<ReportCSVModel> reportCSVModels = progresses.ToList();
var stream = new MemoryStream();
using(var writeFile = new StreamWriter(stream, leaveOpen: true)) {
var csv = new CsvWriter(writeFile, true);
csv.Configuration.RegisterClassMap<GroupReportCSVMap>();
csv.WriteRecords(reportCSVModels);
}
stream.Position = 0; //reset stream
return File(stream, "application/octet-stream", "Reports.csv");
}
//Install Package CsvHelper
//Controller Coding
public async Task<IActionResult> indiainfected(ExcelDownloadIndiaInfected exceldownloadindiainfected)
{
var excel =await downloadReportsRepository.ExcelSheetAddIndiaInfected(exceldownloadindiainfected);
var cc = new CsvConfiguration(new System.Globalization.CultureInfo("en-US"));
var stream = new MemoryStream();
using (var sw = new StreamWriter(stream: stream, encoding: newUTF8Encoding(true)))
{
using (var cw = new CsvWriter(sw, cc))
{
cw.WriteRecords(excel);
}
}
string csvName = $"India_Infected-{DateTime.UtcNow.Ticks}.csv";
return File(stream.ToArray(), "text/csv", csvName);
}
using CsvHelper;
using CsvHelper.Configuration;
namespace projectX.Controllers {
[Route("MyController")]
public class MyController : Controller {
[Route("export")]
[HttpGet]
public ActionResult export() {
var cc = new CsvConfiguration(new System.Globalization.CultureInfo("en-US"));
using (var ms = new MemoryStream()) {
using (var sw = new StreamWriter(stream: ms, encoding: new UTF8Encoding(true))) {
using (var cw = new CsvWriter(sw, cc)) {
cw.WriteRecords(YourGenericList);
}// The stream gets flushed here.
return File(ms.ToArray(), "text/csv", $"export_{DateTime.UtcNow.Ticks}.csv");
}
}
}
}
}
Thanks to Exporting data to CSV from Controller