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

tmaximini picture tmaximini · Jul 24, 2012 · Viewed 7.4k times · Source

I followed the http://railscasts.com/episodes/362-exporting-csv-and-excel and set up an Excel Download in my Rails application.

My controller code looks like this:

  def show
    @project = Project.find(params[:id])
    @project.tasks.order(:name)
    respond_to do |format|
      format.html
      format.json { render json: @project }
      format.xls
    end
  end

and in my view I create the link to download the excel file like this:

.dl_xls= link_to "Download xls", url_for(:format => 'xls')

Now the generated excel file is always named like the id of the Project record, e.g. 80.xls

Is there any way to change this behaviour and give it a custom name?

Thank you..

Answer

cutalion picture cutalion · Jul 24, 2012

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}\""