Tag Archives: Export To Excel

Export Data In Excel Using Visualforce Page

Here in below example I have a VF Page “AccountDetails.vf” with parameter of account Id. In that VF Page I’m showing the Account record respective Contacts. And a button that export the Contact records to excel sheet. Another VF Page “ContactExportToExcel.vf” for excel.

Viualforce Page: AccountDetails.vf

<apex:page standardController="Account" extensions="ContactExportToExcel">
    <apex:form>
        <apex:pageBlock title="Hello {!$User.FirstName}!">
            You are viewing the {!account.name} account.
        </apex:pageBlock>
        <apex:pageBlock title="Contacts">
            <apex:pageBlockTable value="{!account.Contacts}" var="contact">
                <apex:column value="{!contact.Name}"/>
                <apex:column value="{!contact.Email}"/>
                <apex:column value="{!contact.Phone}"/>
            </apex:pageBlockTable>
        </apex:pageBlock>
        
        <apex:commandButton value="Export To Excel" Action="{!ExportToExcel}"/>  
    </apex:form>
</apex:page>

Remember to pass an Account ID as a query string to this page.

Controller:

public with sharing class ContactExportToExcel {
    
    Public List<String> selectedFieldsList {get;set;}
    Public List<Contact> conList {get;set;}
    
    public ContactExportToExcel(ApexPages.StandardController stdCtrl) {
        Account acc = (Account)stdCtrl.getRecord();
        conList = New List<Contact>();
        conList = [Select Id, Name, Email, Phone From Contact Where AccountId =: acc.Id];
    }
    
    Public PageReference ExportToExcel(){
        selectedFieldsList = New List<string>();
        selectedFieldsList.add('Name'); 
        selectedFieldsList.add('Email');
        selectedFieldsList.add('Phone');
        
        PageReference pgRef = New Pagereference('/apex'+'/ContactExportToExcel');
        pgRef.setRedirect(false); 
        return pgRef;
    }
    
}

Visualforce Page: ContactExportToExcel.vf

<apex:page standardController="Account" extensions="ContactExportToExcel" contentType="application/vnd.ms-excel#Contacts.xls" cache="true">
    <apex:pageBlock >
        <apex:pageblocktable value="{!conList }" var="tab">
            <apex:repeat value="{!selectedFieldsList}" var="field">
                <apex:column value="{!tab[field]}"/>
            </apex:repeat>
        </apex:pageblocktable>
    </apex:pageBlock>
</apex:page>

Output: