如何在Ruby on Rails中下载CSV文件?

时间:2022-08-04 23:26:03

In my InvoicesController I have this:

在我的InvoicesController中我有这个:

def index
  @invoices = current_user.invoices
  respond_to do |format|
    format.html
    format.xls
    format.csv # not working!
  end
end

In my index.html.erb view I have these two download links:

在我的index.html.erb视图中,我有以下两个下载链接:

<%= link_to "Download as Excel", invoices_path(:format => "xsl") %>
<%= link_to "Download as CSV", invoices_path(:format => "csv") %>

The templates index.xsl.erb and index.csv.erb do exist as well.

模板index.xsl.erb和index.csv.erb也存在。

The first link works, i.e. the Excel file gets downloaded to the user's computer. However, the CSV file is rendered in the browser and not downloaded.

第一个链接有效,即Excel文件被下载到用户的计算机。但是,CSV文件在浏览器中呈现而不是下载。

What must I do to enable users to download CSV files as well?

我还必须做些什么才能让用户下载CSV文件?

Thanks for any help.

谢谢你的帮助。

3 个解决方案

#1


18  

Try specifying the appropriate content headers and explicitly rendering your index.csv.erb template in your format.csv handler block.

尝试指定相应的内容标头,并在format.csv处理程序块中显式呈现index.csv.erb模板。

# app/controllers/invoices_controller.rb
format.csv do
    response.headers['Content-Type'] = 'text/csv'
    response.headers['Content-Disposition'] = 'attachment; filename=invoice.csv'    
    render :template => "path/to/index.csv.erb"
end

#2


2  

Try this

尝试这个

format.csv do
  response.headers["Content-Type"] = "text/csv; charset=UTF-8; header=present"
  response.headers["Content-Disposition"] = "attachment; filename=invoices.csv"
end

#3


2  

I recently discovered

我最近发现了

render_csv

maybe check out this railscast (yay)

也许看看这个railscast(yay)

#1


18  

Try specifying the appropriate content headers and explicitly rendering your index.csv.erb template in your format.csv handler block.

尝试指定相应的内容标头,并在format.csv处理程序块中显式呈现index.csv.erb模板。

# app/controllers/invoices_controller.rb
format.csv do
    response.headers['Content-Type'] = 'text/csv'
    response.headers['Content-Disposition'] = 'attachment; filename=invoice.csv'    
    render :template => "path/to/index.csv.erb"
end

#2


2  

Try this

尝试这个

format.csv do
  response.headers["Content-Type"] = "text/csv; charset=UTF-8; header=present"
  response.headers["Content-Disposition"] = "attachment; filename=invoices.csv"
end

#3


2  

I recently discovered

我最近发现了

render_csv

maybe check out this railscast (yay)

也许看看这个railscast(yay)