Este dilema se puede tratar de variadas maneras, sin embargo te damos la que en nuestra opinión es la solución más completa.
Solución:
Considere cambiar el enfoque para alinearse más con la sintaxis sugerida actual.
Construya el CSV y devuelva un FileResult, lo que permite que el código no tenga que manipular directamente el Response
objeto.
[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 reportCSVModels = progresses.ToList();
var stream = new MemoryStream();
using(var writeFile = new StreamWriter(stream, leaveOpen: true))
var csv = new CsvWriter(writeFile, true);
csv.Configuration.RegisterClassMap();
csv.WriteRecords(reportCSVModels);
stream.Position = 0; //reset stream
return File(stream, "application/octet-stream", "Reports.csv");
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");
Gracias a la exportación de datos a CSV desde el controlador
¡Haz clic para puntuar esta entrada!
(Votos: 0 Promedio: 0)