Export data by using Apex Code
In Salesforce, we cannot export data from standard or custom reports every time and we cannot export data through data loader every time. In this case, we can write the apex script and run in the anonymous block to export data in .csv
file.
Scenario: Export data from the parent object (Company) which doesn’t have any child (Company members)
Execute below code in the developer console.
List<company__c> extractcompanyMemList = new List<company__c>();
List<company__c> companytList = [select id,name,(select id from companymemebers__r) from company__c];
for(RequestClaimJunction__c company: companytList){
List<companymemeber__c> companyMemList = company.companymemebers__r;
if(companyMemList.size() == 0) {
extractcompanyMemList.add(company);
}
}
String generatedCSVFile ='';
List<String> queryFields = new List<String>{'Id','Partner Account','Status'};
String fileRow = '';
for(company__c company: extractcompanyMemList){
fileRow = '';
fileRow = fileRow +','+ company.Id;
fileRow = fileRow +','+ company.Name;
fileRow = fileRow.replaceFirst(',','');
generatedCSVFile = generatedCSVFile + fileRow + '\n';
}
Messaging.EmailFileAttachment csvAttachment = new Messaging.EmailFileAttachment();
Blob csvBlob = blob.valueOf(generatedCSVFile);
String csvName = 'company details which doesn't have members.csv';
csvAttachment.setFileName(csvName);
csvAttachment.setBody(csvBlob);
Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
String[] toAddresses = new String[]{'Your Email Id'};
String subject = 'company details which doesn't have members CSV';
email.setSubject(subject);
email.setToAddresses(toAddresses);
email.setPlainTextBody('company details which doesn't have members CSV');
email.setFileAttachments(new Messaging.EmailFileAttachment[]{csvAttachment});
Messaging.SendEmailResult[] r = Messaging.sendEmail(new Messaging.SingleEmailMessage[]{email});
While i am working with the above example, recieved heap size limit at for loop
Thanks a lot for sharing this. however you never used the below line of code anywhere and the the result of the csv file does not have comun headers.
list queryFields = new list{‘FirstName’,’LastName’,’EmaployeeNumber’};
I have used similar code to export Apex code to Excel (replace ‘,’ with ‘\t’ ).
Now, I’ve got to format the excel sheet within the Apex code to add a new Tab, format cells and add background color. I am not able to find a solution to this and I do not want to have to create a visualforce page for every excel sheet that I wish to export, since there are many such excel files with different data requirements.
Did you found any way to create multiple sheets in excel to export data?