【问题标题】:rails excel mime-type - how to change default filename?rails excel mime-type - 如何更改默认文件名?
【发布时间】:2012-07-22 13:26:32
【问题描述】:

我关注了http://railscasts.com/episodes/362-exporting-csv-and-excel 并在我的 Rails 应用程序中设置 Excel 下载。

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

  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

有没有办法改变这种行为并给它一个自定义名称?

谢谢你..

【问题讨论】:

    标签: ruby-on-rails mime-types railscasts


    【解决方案1】:
    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

    【讨论】:

    • 谢谢,你节省了我的时间。
    【解决方案2】:

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

    使用标题设置文件名。

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

    【讨论】:

    • 谢谢你这样做。我刚刚将上面引用的行添加到我的 format.xls { ... } 中,它使用指定的文件名。
    • 这适用于任何类型的渲染可下载文件。太好了!
    • 我想补充一点,文件名也应该包含扩展名(在这种情况下为.xls)
    【解决方案3】:

    我希望您实际看到的是没有 .erb 的视图名称,不一定是控制器操作。

    如果您想要这种级别的控制,您可以做三件事。

    • 使用来自控制器的 send_data 调用和制表符分隔的数据,如带有文件名的 rails cast 所示:选项

    例如

    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
    

    这种方法以及 railscast 引入的旧式电子表格ML 语言存在问题,但如果您的用户群被锁定在 MS-OFFICE 中,我认为没有人会注意到。

    • 或者,您可以使用像 act_as_xlsx 或 axlsx_rails 这样的 gem 来消耗 axlsx gem。这些工具生成经过验证的 xlsx 数据(也称为 Office Open XML / ECMA-376 - 或 MS 自 2007 年以来一直在使用的...),并且与其他现代电子表格软件(如 Numbers、GoogleDocs、LibraOffice)具有相当好的互操作性。我相信您在 railscast 中注意到了所有与此相关的 cmets。

    我知道,因为我是作者或 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 也是一个很好的例子,说明如何编写自己的渲染器和响应器,以便您可以使用标准的 rails 视图,但重命名下载的文件。

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

    【讨论】:

    • 感谢您的回答,但我不想走 send_data 路线
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多