Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Salesforce by (11.9k points)

I have a sales force report and what I want is to schedule this report in csv format on daily basis so that the user gets mail with this attachment.

1 Answer

0 votes
by (32.1k points)
edited by

You can schedule the report using the following code:

global class ExporterCSV implements System.Schedulable {

global void execute(SchedulableContext sc) {

List<Merchandise__c> acclist = [Select id , name , CreatedDate , lastModifiedDate from Merchandise__c limit 10];

string header = 'Record Id , Name , Created Date , Modified Date \n';

string finalstr = header ;

for(Merchandise__c a: acclist)

{

   string recordString = a.id + ',' + a.Name + ',' + a.CreatedDate + ',' + a.LastModifiedDate + '\n';

   finalstr = finalstr + recordString;

}

Messaging.EmailFileAttachment csvAttc = new Messaging.EmailFileAttachment();

blob csvBlob = Blob.valueOf(finalstr);

string csvname= 'Invoice.csv';

csvAttc.setFileName(csvname);

csvAttc.setBody(csvBlob);

Messaging.SingleEmailMessage email =new Messaging.SingleEmailMessage();

String[] toAddresses = new list<string> {'[email protected]'};

String subject = 'Merchandise Report CSV';

email.setSubject(subject);

email.setToAddresses( toAddresses );

email.setPlainTextBody('The Merchandise report is attached here.');

email.setFileAttachments(new Messaging.EmailFileAttachment[]{csvAttc});

Messaging.SendEmailResult [] r = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});

  }

}

Become a salesforce certified administrator by going for Intellipaat’s Salesforce online training! 

Welcome to Intellipaat Community. Get your technical queries answered by top developers!

30.4k questions

32.5k answers

500 comments

108k users

Browse Categories

...