function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Lorant DobrondiLorant Dobrondi 

Send Excel file generated by Visualforce page as email attachment

Hello,

I have to send out a weekly report to my sales reps as an Excel file. I initially made a simple CSV file from a scheduled apex class, but I had to add some formatting, so I was forced to go with a Visualforce page instead.

I created the Visualforce page and its controller, and adding the following line to the first row of the Visualforce code enables me to download an .XLS file whenever I access the VF page:
contenttype="application/vnd.ms-excel#TestExport_{!TODAY()}.xls">

Now the hard part: how can I run this visualforce page every week, and email the Excel XLS file to my sales reps?
 
JayantJayant
Create a Schedulable class and schedule it to run every week.
Within the class you can simulate running the VF page and retrieve the output of this VF page programmatically using the getContent() method from PageReference class and send it as an attachment.

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_System_PageReference_getContent.htm
JayantJayant
Check this out too -

https://developer.salesforce.com/docs/atlas.en-us.pages.meta/pages/pages_output_pdf_render_in_apex.htm
 
Lorant DobrondiLorant Dobrondi

Thanks Jayant, that helped!
Now I managed to get the XLS document as an attachment, but now the document itself is plagued by the infamous "The file format and extension of "yourfile.xls" dont' match. The file could be corrupted or unsafe..."

I guess it's more lookin' now.

JayantJayant
I think that issue is still unresolved and xls generated from SFDC always throws it. Not sure if a solution has been found.
Are your users actually going to manipulate these xls files else if they just want to read them, you may instead do a getContentAsPDF() and send a PDF rather than xls as the attachment.