欢迎来到cool的博客
7

Music box

Click to Start

点击头像播放音乐
新博客链接

rails 列表页 如何导出csv文件

列表页如上图

1.在app/helper/application_helper.rb中定义一个导出的方法:

# -*- encoding : utf-8 -*- 
#在controller中一定加上 utf-8

  def generate_csv_order_file orders
    headers = ['用户', '订单号', '商品名', '收货人', '收货地址', '收货电话', '价格', '订单状态']
    file = CSV.generate do |csv|
      # 先放 header
      csv << headers
      # 再放  csv 的内容
      orders.each do |order|
        result = []
        result << order.mobile_user.name
        result << order.order_number
        result << order.good.name
        result << order.receiver_name
        result << order.receiver_address
        result << order.receiver_phone
        result << order.amount
        result << order.order_status_text

        csv << result
      end 
    end 
    send_data file.encode("gbk", "utf-8"), :type => 'text/csv; charset=gbk; header=present', :disposition => "attachment;filename=尚云亿家商城>>订单管理信息.csv"
  end 

2.在orders_controller中添加 export action.

  def export
    @orders = Order.all     
    @orders = @orders.where("order_number like '%#{params[:order_number]}%'") if params[:order_number].present?     #可以按照查询后的结果,导出内容
    @orders = @orders.order("id desc")
    generate_csv_order_file @orders 
  end 

3. 在orders 添加路由 routes:

get :export

4.index 页面添加导出按钮 .

    <div class="search-field">
        <%= link_to export_orders_path(format: "csv", params: params), class: 'btn btn-success sub_button' do%>
            <i class="icon icon-download-alt"></i>导出
        <% end %>
    </div>
 

返回列表