3
votes

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

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.

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

1 Answers

2
votes

You will be extremely limited in how much data can be passed in the 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 common controller class with a non-transient member to deserialize the data into. See PageReference.setRedirect(Boolean)

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

I've put together an example of viewing a CSV via Visualforce - Prototype CSV viewer for Visualforce. You may be able to adapt it to your needs.

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