Print this page

Export data in Excel or PDF format using Visualforce

Knowledge Article Number 000003176
Description

You can get the same information that you normally get in an excel file in a printer friendly PDF format.

Resolution Heads up - The below sample code that loops over Contact ID and Name fields isn't considered production quality and should be subjected to your full development life-cycle, including UAT
  • There may be a requirement to generate lists of Salesforce data outside of the standard reporting interface
  • This is possible using simple Visualforce code
  • The Visualforce page can use the <apex:column> tag to repeat over SObject or custom wrapper class rows
  • The <apex:page> tag should use showHeader="false" renderAs="pdf" orcontentType="application/vnd.ms-excel#SalesForceExport.xls", depending on whether you want a PDF or Excel file
Note: The presence of pageBlock (with or without pageBlockTable) will sometimes produce javascript in the export, so for header information that doesn't need to be in your dataTable, you can use  <table>, <tr> and <td> and other table related HTML tags.

Download PDF Visualforce Page

 
<apex:page controller="contactquery" showHeader="false" renderAs="pdf">
    <apex:pageBlock title="Export Results" >
        <apex:pageBlockTable value="{!cs}" var="contact">
            <apex:column value="{!contact.ID}"/>
            <apex:column value="{!contact.Name}"/>
        </apex:pageBlockTable>
    </apex:pageBlock>
</apex:page>
 

Download Excel Visualforce Page

 
<apex:page controller="contactquery" contentType="application/vnd.ms-excel#SalesForceExport.xls" cache="true">
    <apex:pageBlock title="Export Results" >
        <apex:pageBlockTable value="{!cs}" var="contact">
            <apex:column value="{!contact.ID}"/>
            <apex:column value="{!contact.Name}"/>
        </apex:pageBlockTable>
    </apex:pageBlock>
</apex:page>
 

Query Controller

 
public class contactquery{
    public List<Contact> cs{get; set;}
    public contactquery()
    {
    cs = new List<Contact>();
       for (Contact c : [Select id, Name from Contact])
       {       
           cs.add(c);
       }
    }
}

 




promote demote