I'm using the EPPLus library for my .NET Core 3.1 app; at the moment I'm trying to implement a simple Export
function that makes a sheet based on the given data and instantly downloads it to the users PC.
I've got the following:
public void Export(ProductionLine productionLine, HttpContext context)
{
using (var package = new ExcelPackage())
{
var ws = package.Workbook.Worksheets.Add("MySheet");
ws.Cells["A1"].Value = "This is cell A1";
context.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
context.Response.Headers.Add(
"content-disposition",
string.Format("attachment; filename={0}", "MySheet.xlsx"));
context.Response.SendFileAsync(package);
}
}
The HttpContext
is given via a controller that simply calls the HttpContext controller base. The HttpContext is based on Microsoft.AspNetCore.Http
The current error I've got is cannot convert from 'OfficeOpenXml.ExcelPackage' to 'Microsoft.Extensions.FileProviders.IFileInfo'
logical, but changing the file to IFileInfo
isn't something that's possible I believe.
Is there another way of sending the EPPlus file via a HttpContextResponse?
After fiddling around, it seems that it's easier to use the return File()
function. I've redone my Export
function like so:
public object Export(ProductionLine productionLine, HttpContext context)
{
ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
FileInfo fileName = new FileInfo("ExcellData.xlsx");
using (var package = new OfficeOpenXml.ExcelPackage(fileName))
{
var ws = package.Workbook.Worksheets.Add("MySheet");
ws.Cells["A1"].Value = "This is cell A1";
MemoryStream result = new MemoryStream();
result.Position = 0;
package.SaveAs(result);
return result;
}
And my Controller like this:
public IActionResult ExportCSV([FromQuery] string Orderno)
{
try
{
ProductionLine prodLine = _Prodline_Service.GetAllByOrderno(Orderno);
MemoryStream result = (MemoryStream)_ExcelExportService.Export(prodLine, HttpContext);
// Set memorystream position; if we don't it'll fail
result.Position = 0;
return File(result, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
} catch(Exception e)
{
Console.WriteLine(e);
return null;
}
}