【问题标题】:ModelsController#index is missing a template for this request format and variant. request.formats: ["application/xlsx"] request.variant: []ModelsController#index 缺少此请求格式和变体的模板。 request.formats: ["application/xlsx"] request.variant: []
【发布时间】:2016-11-20 20:26:20
【问题描述】:

希望你一切顺利。 我完全按照this Manual 创建了一个新应用程序并尝试使用 axlsx_rails Gem 导出 excel 文件。这本手册看起来很好而且很完整,但是当我点击 line_to 标记时会弹出这个错误

ProductsController#index is missing a template for this request format and variant. request.formats: ["application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"] request.variant: []

还有这个:

raise ActionController::UnknownFormat, message

我猜这个错误与我的参数或类似的东西有关。 我正在使用 Rails 5 有什么想法吗? 谢谢一百万:)

编辑: 这是我的控制器:

def index
     @products = Product.order('created_at DESC')

     respond_to do |format|
      format.html
      format.xlsx {
        response.headers['Content-Disposition'] = 'attachment; filename="all_products.xlsx"'
      }
     end
  end

查看 index.html.erb

<%= link_to 'Download as .xlsx', products_path(format: :xlsx) %>

查看 index.xlsx.axlsx

  wb = xlsx_package.workbook
    wb.add_worksheet(name: "Products") do |sheet|
      @products.each do |product|
        sheet.add_row [product.title, product.price]
      end
    end

【问题讨论】:

  • 你能显示你的控制器代码吗?
  • @JagjotSingh 当然现在!
  • 点击链接时会生成什么URL?
  • @JagjotSingh 这个/products.xlsx
  • 我自己尝试了整个教程,它似乎运行完美。我只建议您在安装axlsx_rails gem 后重新启动服务器?

标签: ruby-on-rails ruby excel export-to-csv xlsx


【解决方案1】:

这就是解决方案 控制器:

def export_to_excel
    @tests = Test.all
      respond_to do |format|
        format.html
        format.xlsx {
          response.headers['Content-Disposition'] = 'attachment; filename="official_letters.xlsx"'
            }
    end
end

这是 views/ ... export_to_excel.xlsx.axlsx

wb = xlsx_package.workbook
wb.add_worksheet(name: "tests") do |sheet|
  @tests.each do |test|
    sheet.add_row [test.title, test.price]
end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-04
    • 2017-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多