+ Start a Discussion
PopcornappsPopcornapps 

File Storage - Create a Account csv file using Apex. and move to File Storage

Hi,

How can create CSV files Dynamically for example All Contacts and move this file to File Storage.

My Approach (Please Suggest if its right or any alternatives)

 

1. Read to list Contacts.

2. convert data into a string csv. 

3. create a file for the same 

4. move to file storage.

 

 

 

HariDineshHariDinesh

Hi,

 

Below VFP code will help you to create CSV file of contacts.

It will download this file to your system; this might be useful to you.

 

<apex:page standardcontroller="Contact" recordsetvar="Contacts" cache="true" contentType="text/plain/#test.csv">
Name,Email
<apex:repeat value="{!Contacts}" var="con">
{!con.name},{!con.Email}
</apex:repeat>
</apex:page>

If you want more columns you can add columns like  {!con.Phone}...

Save this page and one this page like apex/VFPagename.

Then it will download CSV file to you system.

 

I didn't understand what you mean by Moving file to Storage.

But above code might be useful to you.

Pravin KumarPravin Kumar

Thank You for your Reply.

As I understand there are two storage types.

1. Data Storage 

2. File Storage.

 

Means converting the database records and uploading it in salesforce File storage. We can manually upload files to file storage.but it becomes difficult to maintain

 

Currently I am creating a CSV file as shown in the code and sending it as an attachment in mail. I am stuck how to upload in sales force file storage pragmatically in the controller .

 

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';
csvAttc.setFileName(csvname);
csvAttc.setBody(csvBlob);
Messaging.SingleEmailMessage email =new Messaging.SingleEmailMessage();
String[] toAddresses = new list<string> {'pravinl059@gmail.com'};
String subject ='Account CSV';
email.setSubject(subject);
email.setToAddresses( toAddresses );
email.setPlainTextBody('Account CSV ');
email.setFileAttachments(new Messaging.EmailFileAttachment[]{csvAttc});
Messaging.SendEmailResult [] r = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});

Thanks in advance