Thursday, 14 March 2013

Visualforce To Excel

In this short post I want to explain how we can generate an excel output from a VF page.  We already know to how to generate a PDF from VF page. (Read more to find out how). One of the common requirements is to convert a VF page with data into an Excel sheet, here are some things you may want to keep in mind
  1. Use a separate VF page for export. It is advisable to use a separate VF page to export off, reason being, usually the VF page in which data resides contains buttons, links images etc. and that is not something you usually want in your excel
  2. Use <apex:dataTable> : this gives you a consistent output and works for both windows and MAC. (Thank you Pratyush Kumar  for the Info)
  3. Proper validation : Before the export page is reached, make sure all validations to ensure data will be present is  a good practice
Lets get to the code,
The Design
Here’s a sample data that you may want to download from VF to excel
here’s the code for the above VF, Remember to pass an Account ID as a query string to this page

   <apex:page standardController="Account">
 <apex:pageBlock title="Hello {!$User.FirstName}!">
     You are viewing the {!} account.
  <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}"/>

VF to Excel

Once you’re happy with how the data looks like, its time to convert it into Excel. all you got to do is modify the <apex: page> tag to include the contentType="application/">

<apex:page standardController="Account" contentType="application/">

That’s it, we’re all set. now once you refresh the page you should get the following Excel output,The spreadsheet generated will convert your pageBlockTable to their respective columns, shown here


Known Issues

There is a known issue for this approach in IE. I’ve listed the work-around below, Jeff Douglas had posted it in his blog. Trick is to set the contentType="application/" cache="true"


I hope you found this useful, would love to hear your thoughts in the comments below.

Source :
Post on Developer Force
Jeff Douglas