rails csv导出

1.在helper中定义一个导出方法 不能定义在model中 send_data方法不可以在model中用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# -*- encoding : utf-8 -*-
def generate_csv_by_bonus(cash_desks ,day_array)---传进来的参数
headers = ['品类', '收款台号']-----标题显示
day_array.each do |day|
headers.push(day.strftime("%Y-%m-%d"))
end
file = CSV.generate do |csv|
# 先放 header
csv << headers
# 再放  csv 的内容
cash_desks.each do |cash_desk|
result = []
result << cash_desk.category.name
result << cash_desk.name
day_array.each do |day|
result << cash_desk.sales_checks.where("created_at >= '#{day.beginning_of_day}' and
created_at <= '#{day.end_of_day}'").sum(:award_amount).to_f/100
end
csv << result
end
end
send_data file.encode("gbk", "utf-8"), :type => 'text/csv; charset=gbk; header=present', :disposition => "attachment;filename=欧亚卖场>>收银台统计表.csv"
end

2.在controller中定义一个export方法

1
2
3
4
5
6
7
# -*- encoding : utf-8 -*-
include ApplicationHelper
def export
@cash_desks = CashDesk.where("name not like ?" , '%-removed')
@day_array = SalesCheck.where("created_at >= '#{Settings.from}' and created_at <= '#{Settings.to}'").group('created_at').map{|sales_check| sales_check.created_at.beginning_of_day }.uniq.compact
Tool.generate_csv_by_bonus(@cash_desks ,@day_array)
end

3.在routes.rb中声明这个方法(get)
4.view页面上

1
2
3
4
5
<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>

ps:

1
2
3
4
5
6
CSV.generate(:colsep => '\t', :rowsep => '\r\n') do |csv|
csv << ["登录名称", "真实姓名", "组织机构"]
users.each do |user|
csv << [user.loginname, user.realname, user.categoriesstr]
end
end.encode('gb2312', :invalid => :replace, :undef => :replace, :replace => "?")//解决了下载的csv乱码的bug