Tuesday, January 28, 2014

Export table data in Excel - Salesforce

Here is the easiest way to export table data which is displayed in VF page in excel file.

AccountData.page : VF page which is displaying Accounts data

<apex:page controller="AccountData">
    <apex:form >
        <apex:pageBlock >
            <apex:pageBlockTable value="{!accList}" var="acc">
                <apex:column value="{!acc.Name}"/>
    <apex:column value="{!acc.Type}"/>
    <apex:column value="{!acc.Industry}"/> 
   </apex:pageBlockTable>
        </apex:pageBlock>
    <apex:commandButton value="Export" action="/apex/AccountDataExport"/ >
 </apex:form>
</apex:page>

AccountDataExport.page : VF page which is exporting Accounts data in Excel

Add ContentType attribute in apex page tag and set its value to application/vnd.ms-excel. Here in given example
AccountData.xls is the name of the file.

contentType="application/vnd.ms-excel#AccountData.xls"


<apex:page controller="AccountData" contentType="application/vnd.ms-excel#AccountData.xls">
    <apex:form >
        <apex:pageBlock >
            <apex:pageBlockTable value="{!accList}" var="acc">
                <apex:column value="{!acc.Name}"/>
            </apex:pageBlockTable>
        </apex:pageBlock>
    </apex:form>
</apex:page>

AccountData.cls :

public class AccountData{
    public List<Account> accList{get;set;}
    public AccountData(){
        accList = [Select Name,Type,Industry from Account limit 1000];
    }
}

No comments:

Post a Comment