我在使用axlsx-rails gem生成excel报告时遇到问题,因为我一直在使用Completed 406 Not Acceptable ActionController::UnknownFormat - ActionController::UnknownFormat
。
我在索引视图中有一个带有两个按钮的表单,其中一个提交搜索请求,将搜索结果显示为html表,另一个应允许用户生成带有搜索结果的Excel报表。
我正在使用rails 5.1.6
:
gem 'rubyzip', '>= 1.2.1'
gem 'axlsx', git: 'https://github.com/randym/axlsx.git', ref: 'c8ac844'
gem 'axlsx_rails'
在控制器中:
orders_controller.rb
def index
orders = request.query_string.present? ? Order.search(params,
current_user) : Order.pendientes
if params[:button] == 'report'
@orders = orders
respond_to do |format|
format.xlsx
response.headers['Content-Disposition'] = 'attachment;
filename="Informe_Pedidos.xlsx"'
end
else
@orders = orders.order("#{sort_column} #{sort_direction}").page(params[:page]).per(params[:paginas])
end
end
我还将此添加到mime_types初始化程序中:
Mime::Type.register "application/xlsx", :xlsx
我终于有了这个模板:orders/views/index.xlsx.axlsx
编辑:
视图中的提交按钮逻辑:
<%=button_tag type: 'submit', value: 'report', class: 'btn btn-outline- danger' do %>
<i class="fa fa-download" aria-hidden="true"></i>
<%end%>
这是完整的请求和错误消息:
Started GET "/orders?utf8=%E2%9C%93&f_fin=2018-04-19&f_inicio=& pendientes=true&favoritos=true&planta=&paginas=&bu tton=report&pedido=&sap_cod=&descripcion=&ref=&ot=&desc_ot=&ubicacion=" for 10.0.2.2 at 2018-04-19 17:37:04 +0000
Processing by OrdersController#index as HTML
Parameters: {"utf8"=>"✓", "f_fin"=>"2018-04-19", "f_inicio"=>"", "pendientes"=>"true", "favoritos"=>"true", "pl anta"=>"", "paginas"=>"", "button"=>"report", "pedido"=>"", "sap_cod"=>"", "descripcion"=>"", "ref"=>"", "ot"=>"" , "desc_ot"=>"", "ubicacion"=>""}
User Load (0.1ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2 [ ["id", 1], ["LIMIT", 1]]
Completed 406 Not Acceptable in 3ms (ActiveRecord: 0.1ms)
试试下一个解决方
...
format.xlsx do
render xlsx: "index", filename="Informe_Pedidos"
end
...
这就是我现在在生产应用程序中所拥有的。我可能已经写过了,但它是在一段时间之前,所以除了“它有效”之外,我不能说太多。我相信type
param正在从初始化器中获取mime类型,这与你的相同。希望能帮助到你!
def show
generated_report = GeneratedReport.find(params[:id])
send_data(
generated_report.file_data,
filename: generated_report.filename,
type: :xlsx
)
end
我不知道你是否已经解决了这个问题。但如果没有,请尝试在表单中添加“Format:xlsx”。
例如:
<%= form_for User.new, index_path(format: :xlsx) do |f| %>