Be Good & Do Good!

How to export data to CSV file/text file using Apex

Problem Statement
I want to export list of object into CSV file using Apex

Solution

<apex:page controller="csvController" cache="true" 
contentType="text/csv#filename.csv" language="en-US">
"Col A","Col B","Col C","Col D"
<apex:repeat value="{!myList}" var="a">
"{!a.ColA}","{!a.ColB}","{!a.ColC}","{!a.ColD}"
</apex:repeat>
</apex:page>

Please note that

  • With the #filename.csv, it prompts the user to save/open the file. Otherwise, it loads into the browser as html
  • You’ll also have to format the VF page as a clean csv text file, that means no pageblocktables or anything that might insert html formatting.
  • if customer want to export data object to text file use contentType=”text/plain”

Source : Salesforce Community

7 Comments

  1. Faisal

    your little code snippet helped me.
    thanks

  2. Kerry

    Thanks for this, although a slightly better option is to delimit with tab characters, otherwise you will have problems if your data contains quote characters.

    Use:

    {!a.ColA} {!a.ColB} …

  3. Kerry

    Argh. The tab didn’t render. Use html code: “ampsersand hash 9 semicolon” between the columns

  4. Anil

    Thanks for this , am just trying the solution you have given . Looks helpful, I have question regarding this can we attach and mail this to a user.

  5. miracle

    Description Resource Path Location Type
    Save error: Open quote is expected for attribute “language” associated with an element type “apex:page” in testCsv at line 1 testCsv.page /MY/src/pages line 0 Force.com save problem

  6. raja

    I generated text file ,if i added code it shows same in notepad while viewing ,how to overcome this?

  7. raja

    Hello,I generated text file ,if i added tags in vf page it shows same in notepad while viewing ,how to overcome this?

Leave a Reply

Your email address will not be published. Required fields are marked *