+ Start a Discussion
upenupen 

Export Data to CSV file from Custom Object in salesfroce.

Hello,

 

I want to Export Data to CSV file from Custom object in Salesforce throug Apex Code.

It would be great that anybody provide some sample code.

 

Thanks For Your Co-operation

Best Answer chosen by Admin (Salesforce Developers) 
BritishBoyinDCBritishBoyinDC

This would create a document in a folder called Test with 10 contacts in it...

 

 

String sfilec = 'LastName, FirstName' +  '\n';
String sFolder = 'Test';

List<Contact> cons = [Select Id, FirstName, LastName from Contact limit 10];

for Contact c: cons) {

sfilec += c.LastName + ',' + c.FirstName; 
sfilec += '\n';
}


Id sFolderId = [Select Id From Folder where Name = :sFolder].Id;

Document dn = new Document();

dn.Name = 'TestFile;
dn.FolderId = sFolderId;
dn.Body = Blob.valueOf(sfilec);
dn.ContentType = 'text/plain';
dn.Type = 'txt';
insert dn;

 

 

All Answers

Ritesh AswaneyRitesh Aswaney
You would need to use the apex data loader (setup>data management > dataloader) to get csv outputs of records. It can be run command line and therefore schedulable using an os scheduler such as task manager.
BritishBoyinDCBritishBoyinDC

This would create a document in a folder called Test with 10 contacts in it...

 

 

String sfilec = 'LastName, FirstName' +  '\n';
String sFolder = 'Test';

List<Contact> cons = [Select Id, FirstName, LastName from Contact limit 10];

for Contact c: cons) {

sfilec += c.LastName + ',' + c.FirstName; 
sfilec += '\n';
}


Id sFolderId = [Select Id From Folder where Name = :sFolder].Id;

Document dn = new Document();

dn.Name = 'TestFile;
dn.FolderId = sFolderId;
dn.Body = Blob.valueOf(sfilec);
dn.ContentType = 'text/plain';
dn.Type = 'txt';
insert dn;

 

 

This was selected as the best answer
sfdcfoxsfdcfox

Using Visualforce, you could also create a page that sets the content-type to "text/csv" and output the results to the page; this will prompt the browser to save the file.

upenupen

Thanks a lot BritishBoyinDC.

This sample of code is really very help full..


farukh sk hdfarukh sk hd
How to Download data in csv format using Lightning component.

On my blog i have displayed some data to user, User will select the data that user wants to download from the displayed data. Once user select all those record which user wants to export user has to click on download data button and excel in the csv format will get download.

Also i have shown how to show data from related object in csv as well.

Please refer the below link.


https://www.sfdc-lightning.com/2019/10/export-to-csv-in-lightning-component.html