I have an ASP.NET Core web app with a FilteredStockTableList on my page. I want it to export this to an Excel file and have it downloaded automatically with a button on my .cshtml page. However nothing is prompted on the browser, although the button is successfully clicked.
Here's my button on that .cshtml page:
<button id="exportButton" asp-action="ExportToExcel"
class="btn btn-primary">Export to Excel</button>
Here's my ExportToExcel method:
public IActionResult ExportToExcel(List<StockTable> FilteredStockTableList)
{
using (var package = new ExcelPackage())
{
var worksheet = package.Workbook.Worksheets.Add("StockTableData");
// Set headers
worksheet.Cells["A1"].Value = "Site";
worksheet.Cells["B1"].Value = "Floor";
worksheet.Cells["C1"].Value = "RowIndex";
worksheet.Cells["D1"].Value = "Code";
worksheet.Cells["E1"].Value = "Size";
worksheet.Cells["F1"].Value = "NeededQuantity";
worksheet.Cells["G1"].Value = "Stock2";
worksheet.Cells["H1"].Value = "Stock1";
worksheet.Cells["I1"].Value = "Stock3";
worksheet.Cells["J1"].Value = "Purchase";
worksheet.Cells["K1"].Value = "VersionNumber";
for (int i = 0; i < FilteredStockTableList.Count; i++)
{
var stock = FilteredStockTableList[i];
worksheet.Cells[i + 2, 1].Value = stock.Site;
worksheet.Cells[i + 2, 2].Value = stock.Floor;
worksheet.Cells[i + 2, 3].Value = stock.RowIndex;
worksheet.Cells[i + 2, 4].Value = stock.Code;
worksheet.Cells[i + 2, 5].Value = stock.Size;
worksheet.Cells[i + 2, 6].Value = stock.NeededQuantity;
worksheet.Cells[i + 2, 7].Value = stock.Stock2;
worksheet.Cells[i + 2, 8].Value = stock.Stock1;
worksheet.Cells[i + 2, 9].Value = stock.Stock3;
worksheet.Cells[i + 2, 10].Value = stock.Purchase;
worksheet.Cells[i + 2, 11].Value = stock.VersionNumber;
}
var contentDisposition = new System.Net.Mime.ContentDisposition
{
FileName = "StockTableData.xlsx",
Inline = false,
};
Response.Headers.Add("Content-Disposition", contentDisposition.ToString());
Response.Headers.Add("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
Response.Headers.Add("X-Content-Type-Options", "nosniff");
using (var stream = new MemoryStream())
{
package.SaveAs(stream);
stream.Seek(0, SeekOrigin.Begin);
return File(stream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
}
}
}
And this is my StockTable class:
public class StockTable
{
public string Site { get; set; }
public string Floor { get; set; }
public string RowIndex { get; set; }
public string Code { get; set; }
public string Size { get; set; }
public int NeededQuantity { get; set; }
public int Stock2 { get; set; }
public int Stock1 { get; set; }
public int Stock3 { get; set; }
public int Purchase { get; set; }
public int VersionNumber { get; set; }
}