I get asked quite often about exporting to excel. Well thanks to Visual Force pages we can export data to excel without the use of the Data Loader. There are a number of reasons why you would want to export data to Excel and why using the Data Loader or the Internal features of Salesforce to export data may or may not be what you want. I say this because my example is just going to be a simple one based on a Standard Object and you can easily do this in Salesforce.com from Setup->Data Management->Data Export.

In this case I’m going to show you how to use a Visual Force page to create and automatically download an Excel document. First lets make a simple Visual Force page that lists Account data.

<apex:page standardcontroller="Account" recordsetVar="Acct" sidebar="false">

<apex:form >
    <apex:sectionHeader title="Interview One" />
    <apex:pageBlock title="Accounts">
        <apex:pageBlockTable value="{!Acct}" var="item">
            <apex:column value="{!item.Name}"/>
            <apex:column value="{!item.BillingState}"/>
            <apex:column value="{!item.Phone}"/>
            <apex:column value="{!item.WebSite}"/>
        </apex:pageBlockTable>
    </apex:pageBlock>
</apex:form>
</apex:page>

This page will just display a PageBlockTable of Account data. Now to take this a step further. If we want to export the data in this page to Excel we can do so by modifying the tag. If we set the “contentType” attribute of the tag, then we can deliver a Excel document like so:

<apex:page standardcontroller="Account" recordsetVar="Acct" sidebar="false" contentType="application/vnd.ms-excel#SalesForceExport.xls">

That simple header change will create an Excel file named “SalesForceExport.xls” and will trigger the download when the page is refreshed.

[contact-form]