title: How to generate a csv file from field values of an apex page when clicking a command button in visualforce?
body: <p>I'm working on a visualforce project that requires generating csv file from a group of field values.</p>
  
  <p>I'm using the following code to generate csv, I'm supposed to click on a command button to generate the file but the problem is that when i click save on the apex page an empty file is generated without taking the required data.</p>
  
  <p>Visualforce page:</p>
  
  <pre><code> &lt;apex:page controller="test2" contentType="text/csv#{!fileName}.csv"  showHeader="false"    sidebar="false" standardStylesheets="false"&gt;
        &lt;apex:form &gt;
             &lt;apex:outputText value="{!input}" escape="false"/&gt;
             &lt;apex:commandButton action="{!exportContent}"/&gt;
        &lt;/apex:form&gt;
   &lt;/apex:page&gt;
  </code></pre>
  
  <p>Controller:</p>
  
  <pre><code> public with sharing class test2 {
        // Controller for ExportData.page,
        // which expects to be handed the following POST variables:
        // @inputdata(string) data to export (i.e. in CSV format)
        // @filename(string) name of the file to export, e.g. 'AccountData' 
  
        public transient String input { public get; private set; }
        public transient String fileName { public get; private set; }
  
        public void exportContent(){
             Map&lt;String,String&gt; params = ApexPages.currentPage().getParameters();
  
            // We expect to be handed POST variables called 'inputdata' and 'filename'
            fileName = params.get('filename');
            if (fileName == null) fileName = 'Data';
  
            input = params.get('inputdata');
            if (input == null) input = 'No data provided.';
       }
  }
  </code></pre>