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

How to export data to CSV file using Apex?

Hi all,


Im newbie in, and i have a question, my question is that: i want to export list of object into CSV file using Apex. So please help me how to do this?



Best Answer chosen by Admin (Salesforce Developers) 
Yes, set



All Answers


Any reason you need to use Apex?


You can export data as CSV very easily, either using a report, or the data loader.

Message Edited by Nick34536345 on 01-28-2010 08:46 AM

download Apex Data Loader.

there you get option to export and import the csv file. 

Thanks for your support, i know Data Loader, but i want to develop my visualForce page to export data. Besides, has supported to export list of object data to txt file or not?

I currently have the same requirements too. Try <apex:page ... contentType="text/csv#filename.csv" language="en-US">


(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. For example:



<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>





Thank Wongt,


And if customer want to export data object to text file, so can do that?

Yes, set



This was selected as the best answer

I have tried to do follow this code:


<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">

 It work well when the data i selected < 1000, but when the data select > 1000, the system raise error: 

collection exceeds maximum size: 1001

because the limitation of List<SObject> that contains data. So please help me the solution to solve if in case the data i select > 1000? or have another way to export to CSV with the large data using Apex code?


Chirag MehtaChirag Mehta

With Spring'10 release there's no longer any limitation on List size. Give a try saving your apex with version 18.0


With Spring'10 release there's no longer any limitation on List size. Give a try saving your apex with version 18.0


--->this method is not useful.when the data select > 1000, the system raise error.How can i do?






Can you please tell me the workaround for exporting the csv. I am just unable to make it work




You can use a list of lists and nested repeaters to get around the 1000 records in a list limit. Here's an example:



public class exportCSVController {

    public List<List<myClass>> myList {get;set;}
    public exportCSVController() {
        myList = new List<List<myClass>>();
        List<myClass> temp = new List<myClass>();
        for(Integer i = 0; i < 2500; i++){
            if(temp.size() < 1000){
                myClass m = new myClass();
                m.val1 = 'val1 ' + i;
                m.val2 = 'val2 ' + i;
                temp = new List<myClass>();
                myClass m = new myClass();
                m.val1 = 'val1 ' + i;
                m.val2 = 'val2 ' + i;

    public class myClass{
        public string val1 {get;set;}
        public string val2 {get;set;}

 VisualForce Page:

<apex:page controller="exportCSVController" cache="true" contentType="text/csv#Export.csv" language="en-US">
    "Col A","Col B"
    <apex:repeat value="{!myList}" var="a">
        <apex:repeat value="{!a}" var="asub">

 This should allow you to have up to 10,00,000 records.


Is this generated CSV RFC4180-compliant ? And how can i insert \n or \r in the csv?


Why does the first column always have quotes in the field? How do you remove them? It does export to excel nicely..



    "Col A"Col B
        "val1 0"val2 0
        "val1 1"val2 1
        "val1 2"val2 2
        "val1 3"val2 3
Natavar GhodasaraNatavar Ghodasara
I had tried three methods. When i write in the page like contentType="application/" or contentType="application/octet-stream#record.csv" or contentType="text/csv#filename.csv" it is giing me the code of the page in the cvs file.
Data Loader 5Data Loader 5
You may use a separate service for exporting data from Salesforce into CSV ( - Skyvia. Besides it allows you rich functionality, and it's free.
sandeep madhavsandeep madhav
@Jame_Adapx: Did you got the solution??
David Roberts 4David Roberts 4

Here's an enhancement to Nishad Kallingal's solution at

This example has a custom object on the account. I only wanted accounts that had custom objects so I filtered them in the controller.

[note the limit is in while testing the output to the screen. Put back the csv line when page is working]

public with sharing class vwQuery2ExcelController {
    public List<Account> cs{get; set;}
    public vwQuery2ExcelController()
        cs = new List<Account>();   
       for (Account c : [SELECT,Account.Name, (SELECT licence__c.Id, licence__c.Name FROM Account.Licences__r) FROM Account LIMIT 10])
               if (c.licences__r.isEmpty())   {}

vf Page:
<apex:page Controller="vwQuery2ExcelController" tabStyle="Account"  >
The following parameters have been removed from the apex:page line while testing.
Put back in to get the result exported...
readOnly="true" contentType="application/" cache="true"
Report on a query and send to Excel -->
<!--from Nishad Kallingal -->
<!-- -->
<!-- -->

 <apex:pageBlock title="Export Results" >
  <apex:pageBlockSection title="Accounts with custom object Licence__c" >
        <apex:pageBlockTable value="{!cs}" var="result">
            <apex:column value="{!result.ID}"/>
            <apex:column value="{!result.Name}"/>
               <apex:repeat var="lc" value="{!result.licences__r}">
               <apex:column value="{!lc.Name}"/>   


David Roberts 4David Roberts 4
There's a great solution for export...
Samuel Reyes in
says use the code snippet at
Thanks to Samuel and Douglas!

Also, my query can be refined to only list accounts with contacts by using this format:
SELECT Account.Name, (SELECT Contact.Name FROM contacts) FROM Account WHERE Account.Id IN (SELECT Contact.accountId FROM Contact)
see: and other answers.
David Nash 8David Nash 8
You can use server version of Excel Converter to convert to CSV using APEX. You can check it out here:
Please verify the steps to send Apex Result to Excel.
David Roberts 4David Roberts 4
Use readOnly="true" contentType="application/" cache="true" In your visualforce page header. Got this from Nishad Kallingal but I can’t find the link.
David Roberts 4David Roberts 4
Found it:
Nancy Everest --Nancy Everest --
Super helpful post that worked for me: