function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Anuj Joshi 16Anuj Joshi 16 

Downloading csv file from vf page

Hi All,
I am trying to download csv file when i click on button. But when i click button i am getting like this in csv file.

{"index":93 name:"HideProfileElvVideo" value:false}. Below is my code

VF Page:

<apex:page controller="MyCustomListViewController" contentType="application/vnd.ms-excel#filename.csv">{!header}
<!-- <apex:pageBlock >
<apex:pageBlockTable value="{!Contacts}" var="contact" id="pbt"> 
<apex:column >
<apex:outputField value="{!contact.con.Name}"/>
</apex:column>

<apex:column >
<apex:outputField value="{!contact.con.Account.name}"/> 
</apex:column>
<apex:column >
<apex:outputField value="{!contact.con.Phone}"/>
</apex:column> 
<apex:column >
<apex:outputField value="{!contact.con.Email}"/>
</apex:column> 
</apex:pageBlockTable> 
</apex:pageBlock> -->
<!-- <apex:repeat value="{!Contacts}" var="contact" >
{!contact.con.Name},{!contact.con.Account.name},{!contact.con.Phone},{!contact.con.Email}
</apex:repeat> -->

<apex:pageBlock >
<apex:pageBlockTable value="{!Contacts}" var="contact" id="pbt"> 
{!contact.con.Name},{!contact.con.Account.name},{!contact.con.Phone},{!contact.con.Email}

</apex:pageBlockTable> 
</apex:pageBlock> 
</apex:page>

Rahul KumarRahul Kumar (Salesforce Developers) 
Hi Anuj,

Please refer the below link to Downloading CSV file from vf page. I Hope it will be helpful.

Please mark it as best answer if the information is informative.


Best Regards
Rahul Kumar
Gurpreet Singh PanesarGurpreet Singh Panesar
<apex:page controller="MyCustomListViewController" cache="true" contentType="application/octet-stream#{!fileName}.csv" standardStylesheets="false">
	<apex:pageBlock >
		<apex:pageBlockTable value="{!Contacts}" var="contact" id="pbt"> 
		
		{!contact.con.Name},{!contact.con.Account.name},{!contact.con.Phone},{!contact.con.Email}

		</apex:pageBlockTable> 
	</apex:pageBlock>
</apex:page>
You should try this code :)
Nitesh K.Nitesh K.
Download as CSV, Pdf, Excel, Word
//Visualforce Page
<apex:page controller="AccountFilterctr" renderAs="{!renderAsdoc}"  contentType="{!renderAsExcel}" sidebar="false">

      <Apex:form >  
          <Apex:pageBlock Title="Account" id="pb1" rendered="{!pb1}" >
          
          <style>
           .rg1 {background-color: lightblue; color:black; background-image:none}
           .rg2 {background-color: white; color:black; background-image:none}
           .SelectlistStyle {background-color: lightblue; color:black; font-size: 100%; background-image:none}
           .myClass{
                color:white !important;
                background: #66b3ff !important;
                }
        </style>  
              <Apex:commandButton value="Export as Pdf" action="{!SaveAspdf}" StyleClass="myClass"/>
              <Apex:commandButton value="Export as Excel" action="{!SaveAsExcel}" StyleClass="myClass"/>
              <Apex:commandButton value="Export as Word" action="{!SaveAsWord}" StyleClass="myClass" />
            <Apex:commandButton value="Export as CSV" action="{!SaveAsCSV}" StyleClass="myClass" />


          </Apex:pageBlock>
    
          <Apex:pageBlock >
            <!--Account Table -->
               <apex:outputPanel id="acctTable">
                      <apex:PageblockTable value="{!acct}" var="acc" border="1" cellpadding="2" cellspacing="1" rowClasses="rg1,rg2">
                      
                          <apex:column value="{!acc.Name}">
                          <apex:facet name="header">Account Name</apex:facet>
                          </apex:column>
                          
                          <apex:column value="{!acc.BillingCountry}">
                          <apex:facet name="header">Billing Country</apex:facet>
                          </apex:column>
                          
                          <apex:column value="{!acc.BillingState}">
                          <apex:facet name="header">Billing State</apex:facet>
                          </apex:column>
                          
                          <apex:column value="{!acc.BillingCity }">
                          <apex:facet name="header">Billing City</apex:facet>
                          </apex:column>
                          
                      </apex:PageBlocktable>
                      </apex:outputPanel>
                
          </Apex:pageBlock>
                  
      </Apex:form>

</apex:page>

//Apex class
public class AccountFilterctr 
{
    public List<Account> acct{get;set;}
    public string renderAsdoc{get;set;}
    public boolean pb1{get;set;}
    public string renderAsExcel{get;set;}
 
    public AccountFilterctr()
    {
        acct=[Select Name,BillingCountry,BillingState,BillingCity from Account];
        pb1=true;
    }
    
    //pdf generate
    public PageReference SaveAspdf() {
        pb1=false;
        renderAsdoc='pdf';
        //setup a default file name
        string fileName = 'Account Report Country State City '+date.today()+'.pdf';
        Apexpages.currentPage().getHeaders().put('content-disposition', 'attachemnt; filename='+fileName);
        return null;
    }

    //Save as Excel
    public PageReference SaveAsExcel() {
        pb1=false;
        renderAsExcel='application/vnd.ms-excel#Account Report.xls';
        return null;
    }
    
    // Save as word 
    public PageReference SaveAsWord() {
         pb1=false;
        renderAsExcel='application/vnd.ms-word#Account Report.doc';
        return null;
    }

// Save as CSV
   //Save as Excel
    public PageReference SaveAsCSV() {
        pb1=false;
        renderAsExcel='application/vnd.ms-excel#Account Report.csv';
        return null;
    }

}

Let me know if this helps.

 
Dhruba DebDhruba Deb
Hi, 
Following piece of code worked for me!
<!-- visual force page-->

<apex:page controller="ContactListCon" cache="true" action="{!fetchList}" contentType="application/octet-stream#ListofContact.csv"
           showHeader="false" sidebar="false" standardStylesheets="false">
     
   First name, Last Name, Id 
    <apex:repeat value="{!contacts}" var="a" >       
		 {!a.FirstName},{!a.lastName},{!a.id}
    </apex:repeat>
</apex:page>
//controller for the above VF page

public with sharing class ContactListCon{


public List<contact> contacts {get;set;}
  
    public pageReference fetchList()
    {
         contacts = [SELECT Id,firstname,lastname FROM Contact limit 25];
        return null;
    }  
}


 
Achyut lightningAchyut lightning
Hi Nitesh K, copied u r code and paste in my org ,thats working fine..
In the same way i did as per my requirement but when i am clicking  download button it is downloading VF page only not pageblock table data, i need a file to download as u like .whats the issue?
Plz give a suggestion 
regards,
Achyut,
9676961613.

Note:pls give me quick responce if u have possibility...
Sohit Sharma 4Sohit Sharma 4
I resolved this problem,I am using the javaScript download function in two ways

Visualforce page:
<apex:page controller="VFPageDownloaderController" action="{!downloadAutomatic}">
    <apex:outputText value="{!msg}" escape="false"></apex:outputText>
    
    <script>
  function download(s,filename,ext)
  {
    console.log(s+'Function call');
      const link = document.createElement('a');
  // create a blobURI pointing to our Blob
  link.href = 'data:application/'+ext+';base64,'+s;
  link.download = filename+'.'+ext;
  // some browser needs the anchor to be in the doc
  document.body.append(link);
  link.click();
  link.remove();
  // in case the Blob uses a lot of memory
       setTimeout(() => URL.revokeObjectURL(link.href), 20000);
  }

  </script>
 <apex:outputText value="{!downloadJS}" escape="false"></apex:outputText>
</apex:page>

Visualforce controller:
public class VFPageDownloaderController {
    
    public String msg {get;set;}
    public String downloadJS {get;set;}
    
    //created a function to make the API request
    public void downloadAutomatic(){
        
        String base64String = '';
        
        // download file as a blob from url request
       /* 
        Http http = new Http();
        HttpRequest request = new HttpRequest();
        request.setMethod('GET');
        request.setHeader('Content-Type', 'application/json');
        request.setEndpoint('request url');
       HttpResponse response = http.send(request);
        System.debug(response.getBodyAsBlob());
        Blob b = response.getBodyAsBlob();
          base64String = EncodingUtil.base64Encode(b); */
        
        // download file from ContentVersion
        ContentVersion c = [SELECT Id, VersionData, FileExtension, Title FROM ContentVersion limit 1];
          base64String = EncodingUtil.base64Encode(c.VersionData);
        String fileName = 'abc'; 
        if (base64String == '') {
            msg = 'file Not Found';
        }else {
              downloadJS ='<script> download("'+base64String+'","'+fileName+'","'+c.FileExtension+'"); </script>';
        }     
   } 
}