rails excel mime-type - how to change default filename?

五迷三道 提交于 2019-12-04 11:16:59
cutalion

I believe your answer is here: in rails, how to return records as a csv file

Use headers to set the filename.

headers["Content-Disposition"] = "attachment; filename=\"#{filename}\"" 
akbarbin
def index
  @tabulars = Tabular.all
  filename = "data_users.xls"
  respond_to do |format|
    format.html
    format.xls { headers["Content-Disposition"] = "attachment; filename=\"#{filename}\"" }
  end
end

This link more detail change the file name excel

I expect what you are actually seeing there is the name of the view sans .erb, not necessarily the controller action.

If you want that level of control there are three things you can do.

  • Use the send_data call from your controller with tab separated data as shown in the rails cast with the filename: option

e.g.

class ProductsController < ApplicationController
  def index
    @products = Product.order(:name)
    respond_to do |format|
      format.html
      format.csv { send_data @products.to_csv }
      format.xls { send_data @products.to_csv(col_sep: "\t"), filename: 'your_file_name.xls'}
    end
  end
end

There are problems with this approach as well as the old propriety spreadsheetML language that the railscast introduces, but if your user base is locked into MS-OFFICE, I dont think anyone will notice.

  • Alternatively, you can use a gem like acts_as_xlsx or axlsx_rails that consume the axlsx gem. Those tools generate validated xlsx data (also known as Office Open XML / ECMA-376 - or what MS has been using since office 2007...), and have fairly good interoperability with other modern spreadsheet software like Numbers, GoogleDocs, LibraOffice. I am sure you noticed all the comments related to this in the railscast.

I know, because I am the author or axlsx, and those limitations, and the lack of styling, charts and validation where what drove me to author axlsx in the first place.

More Info: axlsx: https://github.com/randym/axlsx

acts_as_xlsx: http://axlsx.blogspot.jp/2011/12/using-actsasxlsx-to-generate-excel-data.html

  • Write your own responder / renderer

axlsx_rails is also a great example on how to author your own renderer and responder so that you can use the standard rails view, but rename the file that gets downloaded.

https://github.com/straydogstudio/axlsx_rails/blob/master/lib/axlsx_rails/action_controller.rb

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