Ruby on Rails中的send_data与Spreadsheet插件的困难

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

<%= submit_to_remote'submit-button',“Export Report to Excel”,:url => {:controller =>:reports,:action =>:user_report,:print_state =>'print'}%>

在reports_controller中,我使用Spreadsheet插件在user_report函数中生成一个Excel文件。 我想使用send_data将文件stream式传输给用户,而不是先在服务器上创build文件。 我所做的研究表明,使用StringIO是一种方式,如下所示。 令人沮丧的是,当我打电话给send_data时,什么都不会发生。 该插件似乎很好地创build一个文件并将其保存在服务器上,但是当我使用send_file时,什么也不做,表明问题不在于插件。 但是,我在做什么错了send_file / send_data?

函数本身如下所示:

def user_report

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,这是令人困惑的。

我在spreadsheet.rubyforge.org上使用了Rails v2.3,Ruby v1.8.7和Spreadsheet v6.4.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 

即使我不喜欢写和删除,但电子表格似乎是唯一的解决scheme。


  # 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")