I have a requirement to download 4-5 excel file on click of a button from the record detail page, each having different data, along with an image embedded inside the file. Also to create form like structure in the excel file. similar to below -
we are free to use any method - it could either be VisualForce, Aura, LWC. But I would prefer to use LWC. Data will be fetched from different objects.
After searching lot on the internet, I have found 2 ways -
- https://www.apexhours.com/export-to-csv-xls-using-lightning-web-component/
- https://learn.habilelabs.io/salesforce-export-to-excel-with-lightning-web-component-875b3f4b7e53
1st Method
with the first method, I can create an excel sheet, in the desired structure, as data is prepared in HTML format and can be forced to download as follows -
var element = 'data:application/vnd.ms-excel,'+encodeURIComponent(doc);
let downloadElement = document.createElement('a');
downloadElement.href = element;
downloadElement.target = '_self';
downloadElement.download = 'Contact Data.xls';
document.body.appendChild(downloadElement);
downloadElement.click();
where doc
is the variable in which all html data is concatenated. and we can repeat the above line of code with different html variable to download mutliple files.
But the problem is that, it doesn't support image embedding. I had tried to use it as -
doc += '<tr>';
doc += '<td><img src="https://cdn1.vectorstock.com/i/1000x1000/45/00/car-blueprint-vector-7784500.jpg"></td>';
doc += '</tr>';
doc += '</table>';
So this is just a workaround. Excel sheet shows the image when the system is connected to internet. not when offline.
Also one major issue with this method is that - it throws warning everytime file is opened.
Also there is a security threat associated with the xls format (which is wrapped around html) ----- https://social.technet.microsoft.com/Forums/office/en-US/4a15e472-a265-4058-b439-7d79c2670817/xls-file-will-not-open-in-excel-2016-only-gray-view?forum=excel
2nd Method
Now going with the second method (mentioned in the second article link) which uses JavaScript library as a static resource, I can create and download multiple excel sheet in the (.xlsx) format, without any warning, as follows -
async download() {
let _self = this;
// When passing `objects` and `schema`.
await writeXlsxFile(_self.objectsData, {
schema: _self.schemaObj,
fileName: 'file.xlsx'
})
await writeXlsxFile(_self.objectsData, {
schema: _self.schemaObj,
fileName: 'file2.xlsx'
})
}
But it doesn't support image in any way. Also I can't find a way to create form like structure through this way.
Can you all please help me to this sorted-out. Thanks !!