+ Start a Discussion
devsalesforce27devsalesforce27 

Visualforce page : Export Results to Excel or CSV

Visualforce page : Export Results to Excel or CSV

I have created a VF page which fetch the records from object based on the critirea selected by user. Based the critirea I have created a results section in VF page which shows all the relevant information. I have added a custom button " export to excel". Whenever users click this button , it should export all the RESULTS to excel. In order to achieve this , I have created a 2nd VF page same as my original page but with "contentype " attribute. When i click the button , It is exporting the results but It is also exporting the some irrelevant data .
VF Page:
<apex:page controller="Fetchsiteplacement12" tabStyle="Site_Placements__c" sidebar="True" contentType="application/vnd.ms-excel#filename.xls"   language="en-US" cache="True">



    <apex:form >
      
        <apex:pageBlock >
        <apex:messages />
            <apex:pageBlockButtons location="Both">
        
            <apex:commandButton value="Fetch" action="{!FetchSPRec}"/>
            <apex:commandButton value="Cancel" action="{!CancelSPRec}"/>
          
            </apex:pageBlockButtons>
          
          
              <apex:pageBlockSection title="Results">
            <apex:pageBlockSectionItem >
                <apex:pageBlockTable value="{!spRec}" var="site" columnsWidth="500px, 500px" >
                    <apex:column value="{!se.Name}"/>
                    <apex:column value="{!se.Placement__c}"/>
                    <apex:column value="{!se.Level_Max__c}"/>
                  
                 </apex:pageBlockTable>
                 </apex:pageBlockSectionItem>
               
           </apex:pageBlockSection>
        </apex:pageblock>
                </apex:form>
</apex:page>


APex class:

And, in the apex class , I am using this :

public PageReference FetchExcelReport() {
        PageReference nextpage = new PageReference('/apex/ExcelReportPage');
return nextpage;
    }


Below is irrelevent info:

if(!window.sfdcPage){window.sfdcPage = new ApexDetailPage();} UserContext.initialize({"networkId":"","locale":"en_US","labelLastModified":"1393912808000","isDefaultNetwork":true,"today":"3/5/2014 4:23 PM","timeFormat":"h:mm a","userPreferences":[{"index":112,"name":"HideInlineEditSplash","value":false},{"index":114,"name":"OverrideTaskSendNotification","value":false},{"index":115,"name":"DefaultTaskSendNotification","value":false},{"index":119,"name":"HideUserLayoutStdFieldInfo","value":false},{"index":116,"name":"HideRPPWarning","value":false},{"index":87,"name":"HideInlineSchedulingSplash","value":false},{"index":88,"name":"HideCRUCNotification","value":false},{"index":89,"name":"HideNewPLESplash","value":false},{"index":90,"name":"HideNewPLEWarnIE6","value":false},{"index":122,"name":"HideOverrideSharingMessage","value":false},{"index":91,"name":"HideProfileILEWarn","value":false},{"index":93,"name":"HideProfileElvVideo","value":false},{"index":97,"name":"ShowPicklistEditSplash","value":false},{"index":92,"name":"HideDataCategorySplash","value":false},{"index":128,"name":"ShowDealView","value":false},{"index":129,"name":"HideDealViewGuidedTour","value":false},{"index":132,"name":"HideKnowledgeFirstTimeSetupMsg","value":false},{"index":104,"name":"DefaultOffEntityPermsMsg","value":false},{"index":135,"name":"HideNewCsnSplash","value":false},{"index":101,"name":"HideBrowserWarning","value":false},{"index":139,"name":"HideDashboardBuilderGuidedTour","value":false},{"index":140,"name":"HideSchedulingGuidedTour","value":false},{"index":180,"name":"HideReportBuilderGuidedTour","value":true},{"index":183,"name":"HideAssociationQueueCallout","value":false},{"index":194,"name":"HideQTEBanner","value":false},{"index":193,"name":"HideChatterOnboardingSplash","value":true},{"index":195,"name":"HideSecondChatterOnboardingSplash","value":true},{"index":270,"name":"HideIDEGuidedTour","value":true},{"index":282,"name":"HideQueryToolGuidedTour","value":false},{"index":196,"name":"HideCSIGuidedTour","value":true},{"index":271,"name":"HideFewmetGuidedTour","value":false},{"index":272,"name":"HideEditorGuidedTour","value":true},{"index":205,"name":"HideApexTestGuidedTour","value":false},{"index":206,"name":"HideSetupProfileHeaderTour","value":true},{"index":207,"name":"HideSetupProfileObjectsAndTabsTour","value":true},{"index":213,"name":"DefaultOffArticleTypeEntityPermMsg","value":false},{"index":214,"name":"HideSelfInfluenceGetStarted","value":false},{"index":215,"name":"HideOtherInfluenceGetStarted","value":false},{"index":216,"name":"HideFeedToggleGuidedTour","value":false},{"index":268,"name":"ShowChatterTab178GuidedTour","value":false},{"index":275,"name":"HidePeopleTabDeprecationMsg","value":false},{"index":276,"name":"HideGroupTabDeprecationMsg","value":false},{"index":222,"name":"TouchExternalLinkReminderSuppression","value":false},{"index":224,"name":"HideUnifiedSearchGuidedTour","value":true},{"index":226,"name":"ShowDevContextMenu","value":true},{"index":227,"name":"HideWhatRecommenderForActivityQueues","value":false},{"index":228,"name":"HideLiveAgentFirstTimeSetupMsg","value":false},{"index":232,"name":"HideGroupAllowsGuestsMsgOnMemberWidget","value":false},{"index":233,"name":"HideGroupAllowsGuestsMsg","value":false},{"index":234,"name":"HideWhatAreGuestsMsg","value":false},{"index":235,"name":"HideNowAllowGuestsMsg","value":false},{"index":236,"name":"HideSocialAccountsAndContactsGuidedTour","value":false},{"index":237,"name":"HideAnalyticsHomeGuidedTour","value":true},{"index":238,"name":"ShowQuickCreateGuidedTour","value":false},{"index":245,"name":"HideFilePageGuidedTour","value":false},{"index":250,"name":"HideForecastingGuidedTour","value":false},{"index":242,"name":"TouchHideOptoutHover","value":false},{"index":251,"name":"HideBucketFieldGuide","value":false},{"index":263,"name":"HideSmartSearchCallOut","value":true},{"index":265,"name":"HideSocialProfilesKloutSplashScreen","value":false},{"index":273,"name":"ShowForecastingQuotaAttainment","value":false},{"index":280,"name":"HideForecastingQuotaColumn","value":false},{"index":301,"name":"HideManyWhoGuidedTour","value":false},{"index":284,"name":"HideExternalSharingModelGuidedTour","value":false},{"index":298,"name":"HideFileSyncBannerMsg","value":false},{"index":299,"name":"HideTestConsoleGuidedTour","value":true},{"index":300,"name":"HideNetworkSetupOverlayGettingStarted","value":false},{"index":302,"name":"HideManyWhoInlineEditTip","value":false},{"index":303,"name":"HideSetupV2WelcomeMessage","value":false},{"index":312,"name":"ForecastingShowQuantity","value":false},{"index":313,"name":"HideDataImporterIntroMsg","value":false},{"index":314,"name":"HideEnvironmentHubLightbox","value":false},{"index":316,"name":"HideSetupV2GuidedTour","value":false},{"index":317,"name":"HideFileSyncMobileDownloadDialog","value":false},{"index":318,"name":"HideHelpBannerQuickActionList","value":false},{"index":321,"name":"HideCustomEntityQuickActionCallout","value":true},{"index":322,"name":"HideEnhancedProfileHelpBubble","value":false},{"index":328,"name":"ForecastingHideZeroRows","value":false},{"index":330,"name":"HideEmbeddedComponentsFeatureCallout","value":true},{"index":340,"name":"HideS1BrowserUI","value":false}],"orgPreferences":[{"index":257,"name":"TabOrganizer","value":true}],"startOfWeek":"1","isAccessibleMode":false,"ampm":["AM","PM"],"renderMode":"RETRO","userId":"00570000002Nayk","dateTimeFormat":"M/d/yyyy h:mm a","dateFormat":"M/d/yyyy","uiSkin":"Theme3","language":"en_US","siteUrlPrefix":""});


function twistSection(twisty, sectionId) { var parentDiv = twisty; while (parentDiv.tagName != 'DIV') { parentDiv = parentDiv.parentNode; } var div = parentDiv.nextSibling; var elemWasOn = false; if (div.style.display != 'none') { div.style.display = 'none'; twisty.className ='showListButton'; twisty.alt = twisty.title = 'Show Section - '+twisty.name; elemWasOn = true; } else { div.style.display = 'block'; twisty.className = 'hideListButton'; twisty.alt = twisty.title = 'Hide Section - '+twisty.name; } return !elemWasOn; } var registeredSections = new Array(); function registerTwistableSection(headerId, mainTableId) { var obj = new Object(); obj.headerId = headerId; obj.mainTableId = mainTableId; registeredSections[registeredSections.length] = obj; } function twistAllSections(on) { for (var i = 0; i < registeredSections.length; i++) { var obj = registeredSections[i]; var img; img = document.getElementById('img_' + obj.headerId); if (on && 'showListButton' == img.className) { twistSection(img, obj.headerId, obj.mainTableId); } else if (!on && 'hideListButton' == img.className) { twistSection(img, obj.headerId, obj.mainTableId); } } } function toggleSection(headerId, on){ var sectionHead = document.getElementById('head_'+headerId+'_j_id0_j_id1_j_id2'); var body = sectionHead.nextSibling; var disp = on ? 'block' : 'none'; sectionHead.style.display = disp; body.style.display = disp; } function registerTwistableSections_j_id0_j_id1_j_id2() { registerTwistableSection('j_id0_j_id1_j_id2_j_id7', 'j_id0_j_id1_j_id2'); registerTwistableSection('j_id0_j_id1_j_id2_j_id22', 'j_id0_j_id1_j_id2'); registerTwistableSection('j_id0_j_id1_j_id2_j_id27', 'j_id0_j_id1_j_id2'); } registerTwistableSections_j_id0_j_id1_j_id2();


Kindly help me.
Chandra PrakashChandra Prakash
Hello ,

Please see below link of helpful

https://developer.salesforce.com/forums/ForumsMain?id=906F000000096CXIAY

Thanks...
tarunkumarsfdc1.3940961681216885E12tarunkumarsfdc1.3940961681216885E12
Make sure you have the same controller for both of the page and make ur ExcelReportPage code into this and check It will give you the solution.In the place header valuename  please input your colum names.

Make sure you take the backup and do it.

<apex:page controller="Fetchsiteplacement12" tabStyle="Site_Placements__c" sidebar="True" contentType="application/vnd.ms-excel#filename.xls"   language="en-US" cache="True">
    <apex:form >
Headername1,headername2,headername3
      {!se.Name},{!se.Placement__c,{!se.Level_Max__c}
    </apex:form>
</apex:page>

tarunkumarsfdc1.3940961681216885E12tarunkumarsfdc1.3940961681216885E12

      {!se.Name},{!se.Placement__c},{!se.Level_Max__c}
An flower brace is missing in the above code please make a note

devsalesforce27devsalesforce27
@chandra - I already saw that URL. It was of no help. 
@Tarun - I modified the my 2nd VF page with code you mentioned above. This time it was not even exporting the NAME , PLACEMENT AND LEVE_MAX. It was just exporting the irrelevent information.
Below is VF code:

<apex:page controller="Fetchsiteplacement12" tabStyle="Site_Placements__c" sidebar="True" contentType="application/vnd.ms-excel#filename.xls"   language="en-US" cache="True">
    <apex:form >
    <apex:pageblock >
    <apex:pageBlockSection >
     <apex:pageBlockTable value="{!spRec}" var="se" columnsWidth="500px, 500px" >
Name,Site Placement ID,Site Level Max Impressions
      {!se.Name},{!se.Placement__c},{!se.Level_Max__c}
      </apex:pageBlockTable>
      </apex:pageBlockSection>
      </apex:pageblock>
    </apex:form>
</apex:page>


tarunkumarsfdc1.3940961681216885E12tarunkumarsfdc1.3940961681216885E12
Hi devsalesforce27,

try using the content type as contentType="text/csv#doc.csv" and check , I hope this will work for you with out any relevant data.
Jalaj Neelesh ShahJalaj Neelesh Shah
Faced the same issue. Remove the <apex:form> tag and you're good.

Thanks,
Jalaj
NK@BITNK@BIT
You can try this blog..

https://nitinkhunalsalesforce.wordpress.com/2016/10/27/visualforce-export-excel-report-using-remote-action-and-alasql/

You can export excel using javascript remoting, For this you don't need to create additional visualforce page to renderAs excel.
Romel GuerraRomel Guerra
Here is the solution:

http://cloudwharf.com/blog/uncategorized/difficulties-with-generating-an-excel-sheet-to-mac-in-salesforce/