7

コントローラーに、いくつかの仕様を取り込んでレポートを生成する機能があります。この関数 user_report はビューで呼び出されます。

< %= submit_to_remote 'submit-button', "レポートを Excel にエクスポート", :url => { :controller => :reports, :action => :user_report, :print_state => 'print'} % >

reports_controller では、スプレッドシート プラグインを使用して、user_report 関数内で Excel ファイルを生成します。最初にサーバー上でファイルを作成せずに、 send_data を使用してファイルをユーザーにストリーミングしたいと考えています。私が行った調査によると、以下に示すように、StringIO を使用することが最善の方法であることが示されています。イライラすることに、send_data を呼び出しても何も起こりません。プラグインは、ファイルを作成してサーバーに保存するのにうまく機能しているようですが、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 INFO -- Sending data Report_for_jjohnson.xls を読み取りますが、ブラウザーでダウンロードが開始されません。以前、このアプリで send_data を使用することに成功しましたが、これは混乱を招きます。

私は、Rails v2.3、Ruby v1.8.7、Spreadsheet v6.4.1 (spreadsheet.rubyforge.org) を使用しています。

4

2 に答える 2

7

行を変更するだけです:

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
于 2010-10-23T15:53:09.977 に答える
0

書いて削除するのは好きではありませんが、スプレッドシートを使用するのが唯一の解決策のようです。


  # 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")
于 2013-09-06T08:41:38.430 に答える