我使用to_xls和spreadsheet gem将数据导出到rails4中的excel表
但是,即使excel表格打开,我也无法将数据导出到Excel工作表。
我正在学习本教程
orders_controller.rb
def index
@orders = Order.all.includes(:status,:document,:platform, payment:
[:status]).where(status_id: Orders::Status.where(name:
['INPROGRESS', 'COMPLETED']).pluck(:id)).paginate(:page =>
params[:page], :per_page => 30).order('id Desc')
@order_statuses = Orders::Status.all
@delivery_statuses = Orders::DeliveryStatus.all
respond_to do |format|
format.html
format.xls do
send_data(
Order.where(status_id:
Orders::Status.where(name:
['COMPLETED',
'INPROGRESS' ]).pluck(:id))
.includes(:status, :platform,
:payment).map{
|order|
{
id: order.id, txnid: order.txnid,
created_at: order.created_at,
product: order.product,
payment:
order.payment.status.name,
status: order.status.name,
total_amount: order.total_amount,
discount: order.discount,
platform: order.platform.name
}}.to_xls,
content_type: 'application/vnd.ms-excel',
filename: 'orders.xls' )
end
end
end
订单/ index.html.erb
<table id='myOrdersTable'class="table table-bordered">
<thead>
<tr>
<th>Trans ID</th>
<th>Date(dd/mm/yy)</th>
<th>Product</th>
<th>Payment</th>
<th>Status</th>
<th>Total amount</th>
<th>Discount</th>
<th>Platform</th>
<th>Draft</th>
<th>Edit Draft</th>
<th>Upload Soft Copy</th>
<th colspan="3"></th>
</tr>
</thead>
<tbody>
<% @orders.each do |order| %>
<tr>
<td><%= order.txnid %></td>
<td><%= order.created_at.strftime('%d-%b-%Y') %></td>
<td><%= order.product %></td>
<td><%= order.payment.status.name if order.payment %></td>
<td><%= order.status.name %></td>
<td><%= order.total_amount %></td>
<td><%= order.discount %></td>
<td><%= order.platform.name %></td>
<td
:
:
:
<% end %>
</tbody>
</table>
<%= will_paginate @orders %>
:
:
<%#= link_to 'New Order', new_order_path %>
<%= link_to 'Exporting', "/admin/orders.xls", :class =>'btn btn-primary'
%>
此处在链接中,如果调用
<%= link_to 'Exporting', orders_path(request.parameters.merge({:format
=> :xls})), :class =>'btn btn-primary' %>
它给出了一个模板缺失错误(不知道为什么).Hence我没有在代码中使用上面的链接来获取导出按钮。 这有助于我生成Excel工作表,但无法将index.html.erb页面中的所有列及其值导出到工作表中。只需提供一个空白电子表格。如何将所有这些数据导出到工作表?请帮助!我是一个初学者,如此精心准备,如果需要更多数据,请告诉我。
答案 0 :(得分:0)
My choice is to just manually generate CSV file like this :
@orders = Order.all
header = ["id", "status" // put your header field ]
csv = CSV.generate do |csv|
csv << header
@orders.each do |order|
row = [ordrer.id, order.total_amount //mention your fields here ]
end
csv << row
end