I want to download excel file from base64 text in browser.
I can download pdf file without no problem like below
function downloadPDF(attachment) {
const linkSource = `data:application/pdf;base64,${attachment.base64Txt}`;
const downloadLink = document.createElement('a');
const fileName = `${attachment.name}.pdf`;
downloadLink.href = linkSource;
downloadLink.download = fileName;
downloadLink.click();
}
I tried same way for Excel like below. It downloads file but when I open in excel it says "The file and format extension don’t match". I tried to rename file to xlsx and other excel types. But no luck
function downloadExcel(attachment) {
const linkSource = `data:application/vnd.ms-excel;base64,${attachment.base64Txt}`;
const downloadLink = document.createElement('a');
const fileName = `${attachment.name}.xls`;
downloadLink.href = linkSource;
downloadLink.download = fileName;
downloadLink.click();
}
I am using latest React version.
2
Answers
To download an Excel file from a base64 string in the browser, you can use the same approach as for downloading a PDF file. However, you need to use the correct MIME type for Excel files, which is application/vnd.openxmlformats-officedocument.spreadsheetml.sheet for .xlsx files and application/vnd.ms-excel for .xls files.
There might be a relation to the
MIME Type
orFile Extension
to your issue. If the givenbase64 string
is for a.xlsx file
, then use a differentMIME Type
. The code for PDF seems fine.Excel File MIME Types:
application/vnd.ms-exce
lapplication/vnd.openxmlformats-officedocument.spreadsheetml.sheet
Let’s adapt the Exce code for
.xls
and.xlsx
formats.Code for
.xls
:Code for
.xlsx
:While using those functions you have to call the correct function for the format of the
base64-encoded file
.Also make sure that the
base64 string
is correct and wasn’t modified. When the issue is in thebase64 encoding
itself, then changingMIME types
orFile Extensions
won’t help.