I am exporting some data into csv from org and want to download that file. Now i can just send it to email. Any ideas?

List<Account > acclist = [Select id,name , CreatedDate , lastModifiedDate from Account limit 10];
string header = 'Record Id, Name , Created Date, Modified Date \n';
string finalstr = header ;
for(Account a: acclist)
       string recordString = '"'+a.id+'","'+a.Name+'","'+a.CreatedDate+'","'+a.LastModifiedDate +'"\n';
       finalstr = finalstr +recordString;
Messaging.EmailFileAttachment csvAttc = new Messaging.EmailFileAttachment();
blob csvBlob = Blob.valueOf(finalstr);
string csvname= 'Account.csv';
Messaging.SingleEmailMessage email =new Messaging.SingleEmailMessage();
String[] toAddresses = new list<string> {'test@test.com'};
String subject ='Account CSV';
email.setToAddresses( toAddresses );
email.setPlainTextBody('Account CSV ');
email.setFileAttachments(new Messaging.EmailFileAttachment[]{csvAttc});
Messaging.SendEmailResult [] r = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});

Assuming that your email solution is working and that your question is "how can I get this information without needing to send it in an email?"

The easiest way would probably be to use the Salesforce-provided Data Loader (or some similar tool). The "export" option allows you to choose an SObject, choose a location and name for the CSV file it'll generate, and then you could simply copy/paste your query into it.

Also easy would be to remove all of your EmailMessage related code and simply system.debug(finalStr);. If you run this in the developer console, right-click the log that it generates, and select "open raw log", it'll give you the entire string (instead of concatenating the output and/or putting timestamps and "USER DEBUG" at the start of every line).

Beyond that, you'd need to look at using something like a Visualforce page (if you want a button to click) or storing it as a ContentDocument (well, a ContentDocumentVersion).

  • Got it, thanks.
    – Terdivi
    Oct 19 at 14:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.