20

在我的InvoicesController我有这个:

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

在我index.html.erb看来,我有这两个下载链接:

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

模板index.xsl.erbindex.csv.erb确实存在。

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

我必须怎么做才能使用户也能够下载 CSV 文件?

谢谢你的帮助。

4

4 回答 4

30

尝试指定适当的内容标题在处理程序块 中显式呈现您的index.csv.erb模板。format.csv

# 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
于 2013-06-10T09:38:12.297 回答
6

尝试这个

format.csv do
  response.headers["Content-Type"] = "text/csv; charset=UTF-8; header=present"
  response.headers["Content-Disposition"] = "attachment; filename=invoices.csv"
end
于 2013-06-09T23:01:53.120 回答
2

我最近发现

render_csv

也许看看这个railscast(耶)

于 2014-05-23T22:58:38.643 回答
0

我找到了其他适合我的解决方案(Rails 3.2 和 Ruby 2.3.3)

  1. 生成csv后

report_csv = CSV.generate(col_sep: ";")...

  1. 它可以从控制器下载:

format.csv在我们可以使用 的块内send_data(report_csv, filename: 'banana.csv')

  1. 我们可以从目标为空白的链接访问此操作
于 2021-11-03T22:58:06.493 回答