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>

5 comments:

  1. Awesome post! Also liked the dynamic display of columns in page block table used.

    ReplyDelete
  2. Hi,

    Here with out clicking on button excel sheet has opened on load,can you please post how to open excel sheet when i click on button

    ReplyDelete
  3. The code gives me with all HTMl tags.. <> if(!window.sfdcPage) { window.sfdcPage = new ApexPage(); }UserContext.initialize({"ampm":["AM"....etc

    Does this happens after this Spring 17 update..?

    ReplyDelete
  4. Does this code fails after this speing 17 update..

    i get all HTMl tags in excel

    <> if(!window.sfdcPage) { window.sfdcPage = new ApexPage(); }UserContext.initialize({"ampm":["AM"

    ReplyDelete