Activity Forums Salesforce® Discussions How can we generate an Excel file of report to send as an attachment in scheduled E-mail?

  • Manpreet

    Member
    March 23, 2017 at 12:55 pm

    Hi Pranav,

    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[] { '[email protected]' } );
    Messaging.sendEmail( new Messaging.SingleEmailMessage[] { message } );

    }
    }

    Here's an example schedulable class that might be used to email a file. Note that the last five lines need to be ignored or stripped; I'll leave this as an exercise to the reader.

     

    You could also build a SOQL query, execute it, then build the CSV yourself, but that means the system is hard-coded and less flexible. Of course, you could build an interactive configuration (perhaps by the use of a custom object or custom settings), which would help work around that particular limitation of flexibility, but that is by far more complex.

    Thanks.

  • Sergii

    Member
    April 13, 2021 at 4:58 pm

    there are free apps on AppExchagne for this, like Peeklogic Report Sender: https://appexchange.salesforce.com/appxListingDetail?listingId=a0N3u00000MSlAaEAL

Log In to reply.

Popular Salesforce Blogs

Popular Salesforce Videos