2

Please find below code,I am getting attachment in html format. But i need attachment in csv format. Let me know what changes I have to do ?

global class MonthlyScheduler implements System.Schedulable,Database.AllowsCallouts 
    {
        global String ReportId;
        global MonthlyScheduler(String ReportId){
            this.ReportId = ReportId;
        }
        global void execute(SchedulableContext sc) {

            sendNow(this.ReportId);

        }
    @future(callout=true)
    global static void sendNow(String ReportId){

        ApexPages.PageReference report = new ApexPages.PageReference('/'+ReportId+'?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 } );
    }
}
11
  • I pasted the code starting with ApexPages.PageReference in anon apex and it worked fine. Try it w/o the @future.
    – cropredy
    Nov 6, 2019 at 1:55
  • without @future it is giving error
    – Shree
    Nov 6, 2019 at 4:20
  • @cropredy, You got attachment in csv format?
    – Shree
    Nov 6, 2019 at 4:41
  • Yes I did. And it was openable in excel
    – cropredy
    Nov 6, 2019 at 5:05
  • please attach output and code
    – Shree
    Nov 6, 2019 at 5:07

2 Answers 2

1

i did it this way and it works just fine

String instanceName = URL.getSalesforceBaseUrl().toExternalForm();
string url=instanceName+'/servlet/PrintableViewDownloadServlet?isdtp=p1&reportId='+reportId;
ApexPages.PageReference objPage = new ApexPages.PageReference(url);

the only limitation is that i couldn't add filters dynamicaly

0

You need ApexPages.PageReference report = new ApexPages.PageReference('/'+ReportId+'?csv=1&isdtp=p1');

Instead of ApexPages.PageReference report = new ApexPages.PageReference('/'+ReportId+'?csv=1');

I don't know the exact details, but the extra code helps parse the report correctly.

You must log in to answer this question.

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