rails http response to Donwload excel file

女生的网名这么多〃 提交于 2021-01-29 07:45:52

问题


i saw this code in github

require "csv"

csv_str = CSV.generate do |csv|
 csv << ["awesome", "csv"]
end

result = IO.popen("secure-spreadsheet --password secret", "r+") do |io|
 io.write(csv_str)
 io.close_write
 io.read
end

File.open("output.xlsx", "w") { |f| f.write(result) }

this code store a Excel file(output.xlsx) in my project file.

how can i convert this "store file scenario" in to "download the file in the browser"?


回答1:


In your config/initializers/mime_types.rb register the xlsx mime_type(It is not available in Rails by default) :

Mime::Type.register "application/xlsx", :xlsx

Assuming your code that does the excel generation works and is in a controller method(private) named excel_file (I think its better to extract to a service/lib class):

def excel_file
  csv_str = CSV.generate do |csv|
    csv << ["awesome", "csv"]
  end

  IO.popen("secure-spreadsheet --password secret", "r+") do |io|
    io.write(csv_str)
    io.close_write
    io.read
  end
end

In your controller action you should be able to do something like this

def download_excel
  respond_to do |format|
    format.xlsx { send_data excel_file, type: 'application/xlsx; header=present', disposition: "attachment", filename: "output.xlsx"  }
  end
end

( ActionController#send_data "sends the given binary data to the browser". Read more via that link)

If you have a view, you can have a download link

<%= link_to "Download", your_download_path(format: "xlsx") %>

Users should be able to download the excel file via the link



来源:https://stackoverflow.com/questions/64530560/rails-http-response-to-donwload-excel-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!