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 

Create formatted Excel XLS file from weekly scheduled apex class

Hello,

I want to create a weekly report on the leads and their history, and I want to get it in a formatted Excel XLS document. I want this document to be sent to the right people via email (as an attachment)

I managed to achieve something similar to this, but only via a .CSV file, but now I want to be able to color the rows based on some criteria (like if a lead sits in a state for too long etc.)

I scheduled my batch apex class, to run every Friday, and send the email.

Can I achieve something similar to this? I've read a couple of answers that mentioned that I need VisualForce pages for this. How am I able to "schedule" those?
Deepali KulshresthaDeepali Kulshrestha
Hi Lorant, 

global class Exporter implements System.Schedulable {
    global void execute(SchedulableContext sc) {
        ApexPages.PageReference report = new ApexPages.PageReference('/00O500000000000?csv=1');
        Messaging.EmailFileAttachment attachment = new Messaging.EmailFileAttachment();
        attachment.setFileName('report.csv');
        attachment.setBody(report.getContent());
        attachment.setContentType('text/csv');
        Messaging.SingleEmailMessage message = new Messaging.SingleEmailMessage();
        message.setFileAttachments(new Messaging.EmailFileAttachment[] { attachment } );
        message.setSubject('Report');
        message.setPlainTextBody('The report is attached.');
        message.setToAddresses( new String[] { 'asdf@asdf.com' } );
        Messaging.sendEmail( new Messaging.SingleEmailMessage[] { message } );
        
    }
}

I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.

Thanks and Regards,
Deepali Kulshrestha