1

I found this video which shows how to download an xlsx file in my app Download XLSX file Blazor

In nutshell, We use a JS helper which does the job.

//cs file
            iJSRuntime.InvokeAsync<ToSheetConvert>(
                    "saveAsFile",
                    "myfile.xlsx",
                    Convert.ToBase64String(fileContents)
                );


//saveAsFile.js file   
    function saveAsFile(fileName, byteBase64) {
    var link = document.createElement('a');
    link.download = fileName;
    link.href = 'data:application/vnd.openxmlformats-pfficedocument.spreadsheetml.sheet;base64,' + byteBase64;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);

My problem is, this is not working with old version of excel files like .xls, .cvs I think the problem comes from the link.href which is not correct for those extension files... Also don't know which one to put instead... Need to download xls and csv file in blazor

Here the office error message when i try to open the file downloaded Screen KO xls Here when i forced by just changing the extension in the cs File Screen KO xls csfileChange

Daniel Widdis
  • 8,424
  • 13
  • 41
  • 63
Khalid Ab
  • 195
  • 1
  • 3
  • 17

1 Answers1

2

You can replace the href link with the below which should work for all file types:

link.href = "data:application/octet-stream;base64," + bytesBase64;
Umair
  • 4,864
  • 3
  • 28
  • 47
  • i tried to understand why but still not working ... any ideas? **Here the error message :** _We found a problem with some content in "myfile.xls". Do you want us to try to recover as much as we can? If you trust the source of this workbook, click Yes._ I use HSSFWorkbook and HSSFSheet with NPOI ... – Khalid Ab Sep 16 '20 at 08:36
  • Can you create a sample project with a sample excel file and upload somewhere ? – Umair Sep 16 '20 at 08:43
  • thanks Umair, i find the problem and the solution [link](https://stackoverflow.com/questions/10186662/how-can-i-convert-poi-hssfworkbook-to-bytes)... it was because with Invoking HSSFWorkbook.getBytes() does not return all of the data necessary to re- construct a complete Excel file. I use the write method with a ByteArrayOutputStream to get at the byte array and it was OK, Thanks again Umair ! – Khalid Ab Sep 16 '20 at 09:44
  • Hello Umair, i have a similar issue tring to download the xssfworkbook version now, if you can check if you see something ... its here [link](https://stackoverflow.com/questions/63996880/how-to-download-xssfworkbook-file-in-c-sharp-using-npoi) – Khalid Ab Sep 21 '20 at 17:05