【问题标题】:How to generate a csv file from field values of an apex page when clicking a command button in visualforce?单击visualforce中的命令按钮时,如何从顶点页面的字段值生成csv文件?
【发布时间】:2014-11-26 06:54:33
【问题描述】:

我正在处理一个需要从一组字段值生成 csv 文件的 visualforce 项目。

我正在使用以下代码生成 csv,我应该单击命令按钮来生成文件,但问题是当我在 apex 页面上单击保存时,会生成一个空文件,而无需获取所需的数据。

Visualforce 页面:

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

控制器:

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

【问题讨论】:

    标签: csv salesforce visualforce apex


    【解决方案1】:

    使用PageReference.getParameters() 方法可以在查询字符串中传递多少数据将受到极大限制。请注意,此方法仅限于 URL 参数。 POST 变量需要通过具有非瞬态成员的公共控制器类来处理,以将数据反序列化到其中。见PageReference.setRedirect(Boolean)

    如果设置为 false,则重定向是服务器端转发,当且仅当目标页面使用相同的控制器并包含源页面使用的扩展的正确子集时才会保留视图状态。

    我整理了一个通过 Visualforce 查看 CSV 的示例 - Prototype CSV viewer for Visualforce。您可以根据自己的需要进行调整。

    顺便说一句,Salesforce Stackexchange 是询问 Salesforce 特定问题的好地方。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-05
      • 1970-01-01
      • 2011-03-01
      相关资源
      最近更新 更多