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/">{!header}
<!-- <apex:pageBlock >
<apex:pageBlockTable value="{!Contacts}" var="contact" id="pbt"> 
<apex:column >
<apex:outputField value="{!contact.con.Name}"/>

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

<apex:pageBlock >
<apex:pageBlockTable value="{!Contacts}" var="contact" id="pbt"> 


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"> 

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}" >
           .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}
                color:white !important;
                background: #66b3ff !important;
              <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 >
            <!--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 value="{!acc.BillingCountry}">
                          <apex:facet name="header">Billing Country</apex:facet>
                          <apex:column value="{!acc.BillingState}">
                          <apex:facet name="header">Billing State</apex:facet>
                          <apex:column value="{!acc.BillingCity }">
                          <apex:facet name="header">Billing City</apex:facet>


//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];
    //pdf generate
    public PageReference SaveAspdf() {
        //setup a default file name
        string fileName = 'Account Report Country State City ''.pdf';
        Apexpages.currentPage().getHeaders().put('content-disposition', 'attachemnt; filename='+fileName);
        return null;

    //Save as Excel
    public PageReference SaveAsExcel() {
        renderAsExcel='application/ Report.xls';
        return null;
    // Save as word 
    public PageReference SaveAsWord() {
        renderAsExcel='application/ Report.doc';
        return null;

// Save as CSV
   //Save as Excel
    public PageReference SaveAsCSV() {
        renderAsExcel='application/ Report.csv';
        return null;


Let me know if this helps.

Dhruba DebDhruba Deb
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" >       
//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 

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>
  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; = filename+'.'+ext;
  // some browser needs the anchor to be in the doc
  // in case the Blob uses a lot of memory
       setTimeout(() => URL.revokeObjectURL(link.href), 20000);

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

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.setHeader('Content-Type', 'application/json');
        request.setEndpoint('request url');
       HttpResponse response = http.send(request);
        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>';