Showing posts with label Object Field Label. Show all posts
Showing posts with label Object Field Label. Show all posts

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