My C# ASP.NET MVC5 application has a model named Ticket. I want to export all of the tickets in my database to an excel spreadsheet using ClosedXML. I have an Action just for exporting and downloading the data to the spreadsheet. Everything is working great, except when I open my newly downloaded spreadsheet I only have one ticket in there. I think I don't have something just right with my foreach loop. What am I doing wrong?
My action that is called when the user wants to download tickets:
public ActionResult DownloadTickets()
{
string date = "";
string title = "";
string createdBy = "";
bool isCallBack = true;
using (var wb = new XLWorkbook())
{
var ticket = _context.Tickets.ToList();
var dateForXcellSheet = DateTime.Now;
var worksheet = wb.Worksheets.Add("Sample Sheet");
foreach (var i in ticket)
{
date = i.DateCreated.ToString();
title = i.Title;
createdBy = i.CreatedBy;
isCallBack = i.IsCallBack;
}
worksheet.Cell("A1").Value = date;
worksheet.Cell("B1").Value = title;
worksheet.Cell("C1").Value = createdBy;
worksheet.Cell("D1").Value = isCallBack;
// Add ClosedXML.Extensions in your using declarations
return wb.Deliver("tickets-" + dateForXcellSheet + ".xlsx");
}
}