function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Heather_HansonHeather_Hanson 

Help with exporting related list to .csv

Hi, I've spent the morning researching and am still stuck trying to figure out where to begin.

I found a great resource at: https://douglascayers.com/2016/03/20/salesforce-easy-ways-to-export-data-as-csv/ (https://douglascayers.com/2016/03/20/salesforce-easy-ways-to-export-data-as-csv/)

But I'm not sure how to work it to my purpose. I have a custom object: Programming__c and I want to pull the related list records of User_List__c as a CSV.  It doesn't need to be saved as a content delivery (I don't need that taking up my file storage) so I would like it to be accessed through a custom button / visualforce page where the user can download it and save to desktop.

So my two problems are this:
I'm not sure how to properly formulate the class to work for me. I know that is just a snippet so I likely need to wrap it in something like public class UserList{}, but I'm not sure what to do next because I'm still getting errors.  Any help adjusting this would be greatly appreciated.

Once I get my class working, I'm not sure exactly how to call it on my visualforce page to avoid any styling.  Any help would be so appreciated!

My code that I've been working on is below:

Class:
public class ExportUserList{

public String csv = 'Id,Name\n';
for ( List<User_List__c> ul : [ SELECT id, First_Name__c FROM User_List__c ] ) {
  for ( User_List__c ul : ul) {
    csv += ul.id + ',' + ul.First_Name__c.escapeCsv() + '\n';
  }
}
    
 
ContentVersion file = new ContentVersion(
  title = 'userList.csv',
  versionData = Blob.valueOf( csv ),
  pathOnClient = '/userList.csv'
);
 
insert file;
System.debug( file );
}


Visualforce (not much to show since I'm not sure what tags to use to avoid any styling)
 
<apex:page controller='ExportUserList' contentType='application/octet-stream#User_List.csv' showHeader="false">

</apex:page>