Tuesday, March 3, 2015

How to export data in Excel or PDF format using Visualforce

How to export data in Excel or PDF format using Visualforce
***********************************************************

=========================================================
To 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 (Query the data you need)
=========================================================

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);
       }
    }
}

***********************************************************
Thanks Salesforce Knowledge Article

Salesforce - Generate dynamic inner query to fetch parent and related child records

Use Case: In many scenarios, we need to clone the records with related child records. Issue / Limitation: We may simply use the "cl...