0

I am trying to export non-printable report into .XLSX format and send it to external users via email. Exporting to CSV works fine, but when I try to export the same with .XSLX format, I am getting the attachment either in corrupt state or an unformatted state.

Is it possible to export a report in .xslx format?

Below is my code snippet, I am trying out with different combinations of report URL and content type, but none of them worked. Please help if there is any way forword for this?

String reportId = '00O1700000*****';
String instanceName = System.URL.getSalesforceBaseUrl().toExternalForm();
string url=instanceName+'/'+reportId+'?excel=1'; // Not working
//string url=instanceName+'/'+reportId+'?export&xf=xls'; // Not working
//string url=instanceName+'/'+reportId+'?csv=1&isdtp=p1'; //Not working
ApexPages.PageReference report = new ApexPages.PageReference(url);
Messaging.SingleEmailMessage email =new Messaging.SingleEmailMessage();
List<Messaging.EmailFileAttachment> csvAttcList = new List<Messaging.EmailFileAttachment>();
Messaging.EmailFileAttachment csvAttc = new Messaging.EmailFileAttachment();
String mailBody = 'Please find the attachment for daily case report.';
csvAttc.setFileName('Daily Case Report.xlsx');
csvAttc.setBody(report.getContent());
csvAttc.setContentType('text/vnd.openxmlformats'); //Not working
//csvAttc.setContentType('text/csvs'); //Not working
//csvAttc.setContentType('application/vnd.ms-excel'); //Not working
csvAttcList.add(csvAttc);
email.setSubject('Daily Case Report on '+System.now());
List<String> toAddress = new List<String>();
toAddress.add('[email protected]');
email.setToAddresses( toAddress );
email.setPlainTextBody(mailBody);
email.setFileAttachments(csvAttcList);
Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});

1 Answer 1

1

The short answer is that this isn't possible in Apex.

Salesforce generally doesn't have the ability to make .xls or .xlsx files on-platform.

Caspar Harmer goes into some detail about doing this for Visualforce pages (I have no affiliation with Soliant Consulting). This other Q&A also contains good information about why this is between "really hard" and "impossible"

1
  • Gist is since backend doesn't produce excel file/zip files etc, we need to take it to front end and then use JS libraries to give us the relevant converted file.
    – Ysr Shk
    Jan 23 at 7:22

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .