Saturday 28 May 2016

Visualforce page in Excel form



Salesforce allows to deliver a prticular page in Excel form. You only have to define the page content type in the page attribute. Suppose you want to extract the excel on abutton click you will need to open that page (with content type as excel) on button click you will need to return that page in a methode of the class.

I have created an example for you to explain this as follows: I have a vf page with a button that opens a excel sheet with 10 contact records.



VF page name: "Open_Xcel_Page"

<apex:page standardController="Account" extensions="XcelExtract_Contacts_Controller">
  <apex:form >
    <apex:commandButton value="Open Excel" Action="{!OpenExcelSheet}"/>  
 </apex:form>
</apex:page>


Controller

public with sharing class XcelExtract_Contacts_Controller {
Public List<String> selectedFieldsList{get;set;}
Public List<contact> conList {get;set;}
   public XcelExtract_Contacts_Controller(ApexPages.StandardController controller) {
     conList = New List<Contact>();
      conList = [select name,id,birthdate from contact limit 10];
   }

   Public PageReference OpenExcelSheet(){
     selectedFieldsList = New List<string>();
     
       selectedFieldsList.add('name'); 
       selectedFieldsList.add('Id');
       selectedFieldsList.add('Birthdate');
    
    PageReference OpenNewPage = New Pagereference('/apex'+'/Open_Xcel_Page');
    OpenNewPage.setRedirect(false); 
    return OpenNewPage;
   }

}


Excel delivered vf page:

<apex:page standardController="Account" extensions="XcelExtract_Contacts_Controller" 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>

O/P:


No comments:

Post a Comment