csv xls使用respond_to电子表格导出到excel

时间:2011-04-18 16:53:07

标签: ruby-on-rails ruby csv xls

我想将我的rails应用生成的结果导出为ex​​cel格式。 distribution_sheet,结果和标本都是模型。这是我的控制器中的脚本:

    def first

  @distribution_sheet = DistributionSheet.find(:all, :conditions => ["lifecycle_state = ?","closed"]).last

  @results = @distribution_sheet.results

  @specimens = @distribution_sheet.specimens

 end

  include DisplayResultHelper
    def show
     respond_to do |format|
       format.html
        format.csv {
          @specimens.each do |sp|
         send_data(generate_csv([["Lab No","Assay","Batch","Cuttoff"],[sp.id]]),
 :filename => "my_data-#{Time.now.to_date.to_s}.csv",
         :type => 'text/csv')
          end
                   }
         format.xls{
         send_data(generate_xls([["Lab No","Assay","Batch","Cuttoff"],[]]),
         :filename => 'my_date.xls',
         :type => 'application/vnd.ms-excel')
             }

      end
    end
  end

如果我在数组中添加任何单词,这是有效的,但是一旦我添加sp.id就失败了。我想在sp.id中添加数据。有线索吗?

标记

1 个答案:

答案 0 :(得分:2)

我不确定您使用的是哪个库 - 但也许它需要在这些数组中使用真正的字符串,因此请尝试传入sp.id.to_s而不仅仅是sp.id