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});