I have the following code to download data from sql in an excel, the problem is that it downloads the empty excel, only with the headers, I already debugged it and the query if it brings me data. I have guided myself with this tutorial but I don't know what I have done wrong. I have declared this int rowStart = 42; because my query returns 42 rows
public void ExportToExcel()
{
ExcelPackage excel = new ExcelPackage();
ExcelWorksheet ws = excel.Workbook.Worksheets.Add("Report");
ws.Cells["A1"].Value = "Titulo";
ws.Cells["A2"].Value = "Id";
ws.Cells["B2"].Value = "Nombre";
ws.Cells["C2"].Value = "Edad";
var data = bd.Database.SqlQuery<MyClass>("Select ...").ToList();
int rowStart = 42;
foreach (var item in data)
{
ws.Cells[string.Format("A{0}", rowStart)].Value = item.Id;
ws.Cells[string.Format("B{0}", rowStart)].Value = item.Nombre;
ws.Cells[string.Format("C{0}", rowStart)].Value = item.Edad;
rowStart++;
}
ws.Cells["A:AZ"].AutoFitColumns();
Response.Clear();
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment: filename=" + "ExcelReport.xlsx");
Response.BinaryWrite(excel.GetAsByteArray());
Response.End();
}
Try to start the variable rowStart at 3 if you start it at 42 your data will start to show from line 42 check your files below.
Changing the variable to start at 3 looks like this:
I attach the code I use, it is an api method in .net core:
I hope it helps you.