Andreas Lyngstad
Andreas Lyngstad

Reputation: 4927

Rails 3 CSV and XLS export doesn't give file extension

My users can generate a report of some data, and decide what format they want.

They can choose HTML,CSV or XLS

This is the form (Omitted the data stuff, this is just the format selector)

<%= form_tag "/report", :method => :get %>
    Format <select id='format' name='format'>
                <option value='html' selected='selected'>View in browser (HTML)</option>
                <option value='csv'>Export to CSV file</option>
                <option value='xls'>Export to exel (XLS)</option>
            </select>

<%= submit_tag "Make report", :class => 'submit' %>

This form goes to this action

def report
    #...Again omitting data stuff
    respond_to do |format|
      format.html
      format.csv 
      format.xls 
    end
  end

I have corresponding view files.

Like report.xls.erb

In my log I get

Processing by ..Controller#report as XLS

But, the browser downloads the file without extension.

If I change the form_tag line to this.

<%= form_tag "/report.xls", :method => :get %>

The file gets the .xls extension.

I have set the xls mime_types

How can I set the format in the form?

Upvotes: 2

Views: 1649

Answers (1)

Montas
Montas

Reputation: 694

This is from different question.

You can set header to tell browser name of the file.

format.xls do
  response.headers['Content-Disposition'] = 'attachment; filename="' + filename + '.xls"'
  render "report.xls.erb"
end

Upvotes: 6

Related Questions