I'm attempting to export some information from my Blazor page to an Excel workbook. However, I receive the following error message when I attempt to access the file:
excel cannot open the file because the file format or extension is not valid
When I open the file in notepad++ I get see a bunch of letters and signs but no valid data.
My code:
public byte[] SaveSearchToExcel(List<EquipmentForm> EquipmentForms)
{
var wb = new XLWorkbook();
var ws = wb.Worksheets.Add("Search Results");
ws.Cell(1, 1).Value = "TLV Number";
ws.Cell(1, 2).Value = "Descirption";
for(int row = 0; row < EquipmentForms.Count; row++)
{
ws.Cell(row + 1, 1).Value = EquipmentForms[row].TLVNumber;
ws.Cell(row+1, 2).Value = EquipmentForms[row].Description;
}
MemoryStream XLSStream = new();
wb.SaveAs(XLSStream);
XLSStream.Position = 0;
return XLSStream.ToArray();
}
private async void SaveToExcel(){
var XLSStream= _saveToExcel.SaveSearchToExcel(EquipmentForms);
await js.InvokeVoidAsync("BlazorDownloadFile", "export.xlsx",Convert.ToBase64String(XLSStream));
}
function BlazorDownloadFile(filename, content) {
// thanks to Geral Barre : https://www.meziantou.net/generating-and-downloading-a-file-in-a-blazor-webassembly-application.htm
// Create the URL
const file = new File([content], filename, { type: "application/octet-stream" });
const exportUrl = URL.createObjectURL(file);
// Create the <a> element and click on it
const a = document.createElement("a");
document.body.appendChild(a);
a.href = exportUrl;
a.download = filename;
a.target = "_self";
a.click();
// We don't need to keep the object url, let's release the memory
// On Safari it seems you need to comment this line... (please let me know if you know why)
URL.revokeObjectURL(exportUrl);
}
What I'm doing wrong here?