问题
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