Thursday, 4 July 2019

Export Apex Result To CSV File

Use Case : Get the Contract object Field Label  and Field Name (API) name & Export that result to CSV file and Send Email Notification.


//To get all the objects details    
Map<String, Schema.SObjectType> schemaMap = Schema.getGlobalDescribe();
Map<String, Schema.SObjectField> fieldMap = schemaMap.get('Contract').getDescribe().fields.getMap();
string header = 'FIELD LABEL , FIELD NAME\n'; //CSV Header Row
string contrExcelStr = header ;

//Loop through the field map and get the object field label & field name(API Name)
for(Schema.SObjectField sfield : fieldMap.Values())
{
 schema.describefieldresult descField = sfield.getDescribe();
 mapResult.put(descField.getLabel(),descField.getname());
 string recordString = descField.getLabel() +','+descField.getname() +'\n';
 contrExcelStr = contrExcelStr +recordString;
}

 //Email Notification
Messaging.EmailFileAttachment contrCsvAttch = new Messaging.EmailFileAttachment();
blob csvBlob = Blob.valueOf(contrExcelStr);
string csvname= 'Contract.csv';
contrCsvAttch.setFileName(csvname);
contrCsvAttch.setBody(csvBlob);
Messaging.SingleEmailMessage email =new Messaging.SingleEmailMessage();
String[] toAddresses = new list<string> {'test@gmail.com'};
String subject ='Contract CSV';
email.setSubject(subject);
email.setToAddresses( toAddresses );
email.setPlainTextBody('Contract CSV ');
email.setFileAttachments(new Messaging.EmailFileAttachment[]{contrCsvAttch});
Messaging.SendEmailResult [] r = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});

//Sent Email 


6 comments:

  1. Very Nice Post! Thank you so much for sharing this informative post, it was so good to read and useful to improve my knowledge as updated one, keep blogging.
    Saleforce Developer Training in Electronic City

    ReplyDelete
  2. Thanks Deepika!! great code!! I only miss the definitio of
    Map mapResult = new Map();

    Thanks a lot! best regards, Jose Fluxa

    ReplyDelete
  3. This comment has been removed by the author.

    ReplyDelete
  4. Great article..
    If instead of metadata, if i want fields as col name and data as records. How would be manipulate this existing code? Thank you

    ReplyDelete
  5. hi, i want to download one [articular record through a Download button on record details page. can you help me how to achive this

    ReplyDelete
  6. Hi Deepika,
    I'm also working on the same requirement and thanks to your blog that I have found the solution but as I'm new to salesforce, so can please help me how to execute it in anonymous window.
    That will be highly appreciated.

    ReplyDelete