2012-07-24 41 views
4

我跟着http://railscasts.com/episodes/362-exporting-csv-and-excel 並在我的Rails應用程序中設置了Excel下載。rails excel mime-type - 如何更改默認文件名?

我的控制器代碼如下所示:

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 

在我看來,我創建下載的Excel文件中像這樣的鏈接:

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

現在生成excel文件總是被命名爲喜歡Project記錄的ID,例如80.xls

有什麼方法可以改變這種行爲並給它一個自定義名稱嗎?

謝謝。

回答

23

我相信你的答案就在這裏:in rails, how to return records as a csv file

使用頁眉設置文件名。

headers["Content-Disposition"] = "attachment; filename=\"#{filename}\"" 
+0

感謝該做的。我只是將上面的引用行添加到我的format.xls {...}中,並且它使用了指定的文件名。 – tmaximini 2012-07-24 13:47:19

+0

這適用於任何類型的呈現可下載文件。大! – 2015-04-18 22:29:08

2

我希望你是什麼實際看到有觀點SANS .erb,不一定是控制器動作的名稱。

如果你想要控制水平,你可以做三件事。

  • 使用從與標籤控制器的SEND_DATA呼叫分隔的數據如圖投與文件名中的軌道:選項

例如

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 

有這種方法的問題,以及舊禮SPREADSHEETML語言的railscast介紹,但如果你的用戶羣鎖定爲MS-OFFICE,我不認爲任何人會注意到。

  • 或者,您可以使用像使用axlsx gem的acts_as_xlsx或axlsx_rails這樣的gem。這些工具生成經過驗證的xlsx數據(也稱爲Office Open XML/ECMA-376--或MS自從2007年以來一直使用的...),並且與Numbers,GoogleDocs,LibraOffice等其他現代電子表格軟件具有相當好的互操作性。我相信你在railscast中注意到了與此相關的所有評論。

我知道,因爲我是作者或axlsx,以及那些限制,以及缺乏造型,圖表和驗證的地方,這些都促使我在第一時間編寫axlsx。

更多信息: axlsx:https://github.com/randym/axlsx

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

  • 寫自己的應答/渲染器

axlsx_rails還對如何編寫自己的渲染一個很好的例子和響應者,以便您可以使用標準欄視圖,但重命名下載的文件。

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

+0

謝謝您的回答,但我不想去SEND_DATA路線 – tmaximini 2012-07-24 13:46:31

2
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 

此鏈接more detail change the file name excel

+0

謝謝,你節省了我的時間。 – 2015-10-30 07:39:51