【问题标题】:Difficulty with send_data in Ruby on Rails in conjunction with Spreadsheet plug-inRuby on Rails 中 send_data 与电子表格插件结合使用的困难
【发布时间】:2011-04-27 03:32:57
【问题描述】:

我在控制器中有一个函数,它接受一些规范并生成关于它们的报告。这个函数 user_report 在视图中被调用:

{ :controller => :reports, :action => :user_report, :print_state => 'print'} % >

在报告控制器中,我使用电子表格插件在 user_report 函数中生成 Excel 文件。我想使用 send_data 将文件流式传输给用户,而无需先在服务器上创建它。我所做的研究表明,使用 StringIO 是可行的方法,如下所示。令人沮丧的是,当我调用 send_data 时没有任何反应。该插件似乎可以很好地创建文件并将其保存在服务器上,但是当我使用 send_file 时什么也没做,这表明问题不在于插件。但是我在 send_file/send_data 上做错了什么?

函数本身如下所示:

定义用户报告

if request.post?
  unless params[:reports][:userid].blank?
    @userid=params[:reports][:userid]
  end
  if params[:print_state]=='print'  

    report = Spreadsheet::Workbook.new
    info = report.create_worksheet :name => 'User Information'
    info.row(1).push 'User ID', @userid

    @outfile = "Report_for_#{@userid}.xls"

    require 'stringio'
    data = StringIO.new ''
    report.write data
    send_data data.string, :type=>"application/excel", :disposition=>'attachment', :filename => @outfile
  end

  respond_to do |format|
    format.js { }
  end
end

结束

日志文件读取 2010-10-18 14:13:59 信息——发送数据 Report_for_jjohnson.xls 但在浏览器中没有开始下载。我之前在这个应用上成功使用过 send_data,这很令人困惑。

我在电子表格.rubyforge.org 上使用 Rails v2.3、Ruby v1.8.7 和电子表格 v6.4.1。

【问题讨论】:

    标签: ruby-on-rails excel spreadsheet xml-spreadsheet


    【解决方案1】:

    只需换行:

    send_data data.string, :type=>"application/excel", :disposition=>'attachment', :filename => @outfile
    

    到:

    send_data data.string.bytes.to_a.pack("C*"), :type=>"application/excel", :disposition=>'attachment', :filename => @outfile
    

    【讨论】:

    • 这是一个老问题...但我有一种冲动注意到data.string.force_encoding('binary') 对我有用并且看起来更好一些。
    【解决方案2】:

    虽然我不喜欢写和删除,但电子表格似乎是唯一的解决方案。


      # write the file
    
     book.write "Employee_History_#{ params[:id]}.xls"
    
     # send the file
    
     send_file "Employee_History_#{ params[:id]}.xls", :type => "application/vnd.ms-excel", :filename => "data.xls", :stream => false
    
     # and then delete the file
    
     File.delete("Employee_History_#{ params[:id]}.xls")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-07-31
      • 1970-01-01
      • 1970-01-01
      • 2011-07-29
      • 1970-01-01
      • 2012-05-11
      • 1970-01-01
      • 2015-06-01
      相关资源
      最近更新 更多