This works!
private Stream GetFileStream()
{
var trustedFileName = "Orders.xlsx";
return File.OpenRead(Path.Combine(Environment.ContentRootPath,
Environment.EnvironmentName, "unsafe_downloads", trustedFileName));
}
private async Task DownloadFileFromStream()
{
await AddVendorsToExcel();
var fileStream = GetFileStream();
var fileName = "Orders.xlsx";
using var streamRef = new DotNetStreamReference(stream: fileStream);
await JS.InvokeVoidAsync("downloadFileFromStream", fileName, streamRef);
}
private async Task AddVendorsToExcel()
{
ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
var trustedFileName = "Orders.xlsx";
string filePath = Path.Combine(Environment.ContentRootPath,
Environment.EnvironmentName, "unsafe_downloads", trustedFileName);
var file = new FileInfo(filePath);
using var package = new ExcelPackage(file);
int recordIndex = 2;
if (package.Workbook.Worksheets.Count > 1){
package.Workbook.Worksheets.Delete(1);
}
var worksheet = package.Workbook.Worksheets.Add("Vendors");
worksheet.Row(1).Style.Font.Bold = true;
var headerCells = worksheet.Cells["A1:E1"];
headerCells.Style.Font.Bold = true;
headerCells.Style.Font.Size = 13;
headerCells.Style.Border.BorderAround(ExcelBorderStyle.Thin);
headerCells.Style.Border.Top.Style = ExcelBorderStyle.Thin;
headerCells.Style.Border.Left.Style = ExcelBorderStyle.Thin;
headerCells.Style.Border.Right.Style = ExcelBorderStyle.Thin;
headerCells.Style.Border.Bottom.Style = ExcelBorderStyle.Thin;
headerCells.Style.Font.Color.SetColor(System.Drawing.Color.Black);
headerCells = worksheet.Cells["A1:E1"];
headerCells.Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid;
headerCells.Style.Fill.BackgroundColor.SetColor(System.Drawing.Color.LightGray);
worksheet.Cells[1, 1].Value = "Vendor Id";
worksheet.Cells[1, 2].Value = "Name";
worksheet.Cells[1, 3].Value = "Email";
worksheet.Cells[1, 4].Value = "Address";
worksheet.Cells[1, 5].Value = "Responsible Name";
foreach (var vendor in _vendors)
{
worksheet.Cells[recordIndex, 1].Value = vendor.Id;
worksheet.Cells[recordIndex, 1].Style.Font.Bold = true;
worksheet.Cells[recordIndex, 2].Value = vendor.Name;
worksheet.Cells[recordIndex, 3].Value = vendor.Email;
worksheet.Cells[recordIndex, 4].Value = vendor.Address;
worksheet.Cells[recordIndex, 5].Value = vendor.MainResponsibleName;
recordIndex++;
}
worksheet.Cells[worksheet.Dimension.Address].AutoFitColumns();
await package.SaveAsync();
}