How to generate csv file from apex page field values ​​on command button click in visualforce?

I am working on a visualforce project that requires generating a csv file from a group of field values.

I am using the following code to generate the csv, I have to click on the command button to generate the file, but the problem is when I click save on the apex page, an empty file is created with no data needed.

Visualforce page:

 <apex:page controller="test2" contentType="text/csv#{!fileName}.csv"  showHeader="false"    sidebar="false" standardStylesheets="false">
      <apex:form >
           <apex:outputText value="{!input}" escape="false"/>
           <apex:commandButton action="{!exportContent}"/>
      </apex:form>
 </apex:page>

      

Controller:

 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<String,String> 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.';
     }
}

      

+3


source to share


1 answer


You will be extremely limited in how much data can be passed in a query string using the PageReference.getParameters () method . Note that this method is limited to URL parameters. POST variables need to be handled by having a generic controller class with a non-transient element to deserialize data. See PageReference.setRedirect (Boolean)

If set to false, a redirect is a server-side transition that preserves view state if and only if the target page uses the same controller and contains a corresponding subset of the extensions used by the source page.



I put together an example of CSV viewer via Visualforce - Prototype CSV viewer for Visualforce . You may be able to tailor it to your needs.

By the way, the Salesforce Stackexchange is a great place to ask specific Salesforce questions.

+2


source







All Articles