I am trying to download a List of Items as excel from Blazor server side project . I used CsvHelper to generate the byte[] from the list and using the below code to download the byte[] content as excel file .
The code from Blazor Component is like below [ Click event of button to download excel]
@inject IJSRuntime JsRuntime
private async Task ExportToExcel()
{
jobStarted = true;
var fileBytes= ExportHelper.ConvertContactDataToCsv(); // This will return byte[] of contacts
if (await JsRuntime.InvokeAsync<bool>("confirm", $"Do you want to Export?"))
{
var fileName = $"Contacts";
await JsRuntime.InvokeAsync<object>("saveAsFile", fileName, Convert.ToBase64String(fileBytes));
}
jobStarted = false;
}
The Javascript code is like below
window.saveAsFile = function (fileName, byteBase64) {
var link = this.document.createElement('a');
link.download = fileName;
link.href = "data:application/vnd.ms-excel;base64," + byteBase64;
this.document.body.appendChild(link);
link.click();
this.document.body.removeChild(link);
}
Execution of this generates the file without any issues , but while opening the file using Microsoft Excel the warning message is like
The file format and extension of 'Contacts.xls' don't match. The file could be corrupted or unsafe. Unless you trust its source, don't open it. Do you want to open it anyway?
And if i ignore the warning and proceed with opening all contents in excel looks good
Now i tried to generate file with extension xlsx and different mime type inside JS code The changes are like
var fileName = $"Contacts.xlsx";
and inside JS tried these 2 combinations separately
link.href = "data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64," + byteBase64;
link.href = "data:application/octet-stream;base64," + byteBase64;
The code executed without any issues and files getting generated but while opening file the warning is like
Excel cannot open the file 'Contacts.xlsx' because the file format for the file extension is not valid.’ Verify that the file has not been corrupted and that the file extension matches the format of the file
I am not able to open the file at all.
So what is the right MIME type to be used to ensure downloaded excel file can be opened in Excel without warnings
Since you are using CsvHelper (via ConvertContactDataToCsv) your output file is a Comma Separated Value text file, not a binary Excel .xls file.
Don't use the .xls file extension, instead use e.g. .csv;
so Contacts.csv instead of Contacts.xls.
For the mime type, you might use text/csv.
But foremost, it is the wrong file extension that makes Excel error on that file.