1

I am querying some fields of Account objects records. And i am storing them in a list. Now i want to send this data through mail with excel sheet attached(which contains list data of Account Records) on click of send email from VF page. But i am getting the error as blob variable do not exist. Please check the below code.

     List<Account>  ObjectList1 = [SELECT id,Name FROM Account];
     Messaging.EmailFileAttachment csvAttc = new Messaging.EmailFileAttachment();
     blob csvBlob = Blob.valueOf(ObjectList1);
     string csvname= 'Duplicate.xls';
     csvAttc.setFileName(csvname);
     csvAttc.setBody(csvBlob);
     Messaging.SingleEmailMessage email =new Messaging.SingleEmailMessage();
     String toAddresses = 'xyz@abc.com';
     String subject ='Duplicate Data';
     email.setSubject(subject);
     email.setToAddresses( toAddresses );
     email.setPlainTextBody('Duplicate Data');
     email.setFileAttachments(new Messaging.EmailFileAttachment[]{csvAttc});
     Messaging.SendEmailResult [] r = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});
1

There are a couple of bits that won't work in your code:

Blob csvBlob = Blob.valueOf(ObjectList1);

ObjectList1 is List<Account> in your code. Blob.valueof takes String as input. This is the source of your error.

Another error is in this line:

email.setToAddresses(toAddresses);

This method requires input of List<String>, and you are passing a single string.

But I think what you will have the most success by running a report through the Analytics API and generate the results as CSV (String) and then pass it into your Blob.valueof() method. This technique is discussed in another StackExchange question that you can find here.

Generating this through a report gives you the ability to change the data produced in the PDF without changing code. You can also secure access to the report, or open it up to other users to modify, if need be.

  • I accept the mistake in toAddresses part. Cant we do it without using reports as this thing comes in batch class. – sunny Jan 20 '14 at 13:22
  • You could just construct the CSV string in code, I suppose and return that. There are ways you can make an HTTP request to a VF page that renders PDF and then use the body that is returned. But I would always recommend the report option first. It may seem like more work now, but it is much more maintainable in the long run. – pchittum Jan 21 '14 at 12:20
  • If its a string output how do I put into multiple rows in excel ?? – sfdcFanBoy Jan 18 '15 at 14:10
  • Excel can be quite flexible with regards to formatted data in text. office.microsoft.com/en-gb/excel-help/… – pchittum Jan 18 '15 at 23:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.