1

My requirement is to send csv file as email attachment to few email IDs. Currently I can do this but fetching records in single tab of the csv file. My requirement is to get the records in separate tabs in CSV file. Like sObject A in 1st tab, sObject B in 2nd tab, sObject C in 3rd tab and so on base don no .of sObjects. Please help me to get the csv in above format (different sObject in different tab).

My Current working code is given below:-

List<Account> lstFeedback=[SELECT Id,format(CreatedDate),Name from Account order by CreatedDate DESC limit 10];
string header = 'Record Id, Created Date, Name \n';
string finalstr = header;
if(lstFeedback !=null && lstFeedback.size()>0){
   for(Account tst: lstFeedback)
      {
        string recordString = tst.id+','+tst.CreatedDate+','+tst.Name+'\n';
        finalstr = finalstr +recordString;
      }
}
Messaging.EmailFileAttachment csvAttc = new Messaging.EmailFileAttachment();
blob csvBlob = Blob.valueOf(finalstr);
string csvname= 'AccountData_'+system.today().format()+'.csv';
csvAttc.setFileName(csvname);
csvAttc.setBody(csvBlob);
Messaging.SingleEmailMessage email =new Messaging.SingleEmailMessage();
String[] toAddresses = new list<String> {'[email protected]','[email protected]'};
list<string> CcAddresses = new list<string> {'[email protected]'};
String subject ='Account records extract CSV -'+system.today().format();
email.setSubject(subject);
email.setToAddresses(toAddresses);
email.setCCAddresses(CcAddresses);
email.setPlainTextBody('Hi Team,\n\n As requested,PFA the Account record extract fetched today On '+System.Now().format()+' EST from the system.\n\n Thanks,\n HRZ Support.');
email.setFileAttachments(new Messaging.EmailFileAttachment[]{csvAttc});
Messaging.SendEmailResult [] r = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});
System.debug('## Email Send Result..:'+r);

1 Answer 1

1

Torn between making this a comment or an answer...so we'll do an answer.

Standard CSV has no facilities for making multiple "tabs". It's just a simple file format that specifies comma as the column delimiter and newline as the row delimiter.

The price for its simplicity is that it doesn't support features like multiple "sheets" like you'd find in MS Excel.

If you want those extra features, then you'll need to move to a more complex format like xlsx or ods. Trying to do that in Apex, however, is not going to be fun.

You must log in to answer this question.

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