rails 3 excel excel_rails

[url]https://github.com/asanghi/excel_rails[/url]

[quote=""]excel_rails这是对spreadsheet插件的一个扩展。安装 excel_rails必须要安装spreadsheet[/quote]

Gemfile
gem 'spreadsheet'
gem 'excel_rails'


[quote=""]保存后执行[/quote]
bundle install


[quote=""]比如要打印UserController下面的index添加[/quote]
app/controllers/users_controller.rb
def index
@search = User.search(params[:serach])
@users = @search.paginate :page => params[:page],:per_page => 10

respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => @users }
format.xls
end
end


[quote=""]然后在对应视图的文件下面添加一个空白文件名为index.xls.rxls [/quote]
app/views/users/index.xls.rxls
# encoding: utf-8
excel_document(:filename => "#{Time.now.strftime('%Y-%m-%d,%H:%M:%S')}-users.xls") do |workbook|
sheet = workbook.create_worksheet
sheet.name = "What's in a name"

sheet.row(0).concat %w{用户}
# 下面注释的为 可以写入Excel的方法
# sheet[1,0] = 'Japan'
# row = sheet.row(1)
# row.push 'Creator of Ruby'
# row.push 'Creator of rails'
# row.unshift 'Yukihiro Matsumoto'
# sheet.row(5).unshift 'HaHa'
# sheet.row(3).push 'Charles Lowe', 'Author of the ruby-ole Library'
# sheet.row(3).insert 1, 'Unknown'
# sheet.update_row 4, 'Hannes Wyss', 'Switzerland', 'Author'
th = [ '流水号', '客户名称','客户号','金额','通过认证时间','不通过时间','创建时间' ]
sheet.row(1).replace th

sheet.row(0).height = 18
sheet.row(0).height = 18

format = Spreadsheet::Format.new :color => :blue,:weight => :bold,:size => 18

sheet.row(0).default_format = format

# 设置表格的标题栏为粗体
bold = Spreadsheet::Format.new :weight => :bold,:horizontal_align => :center
th.length.times do |x| sheet.row(1).set_format(x, bold) end

@search.all.each_with_index do |user,index|
sheet.row(index + 2).push user.id,user.user_name,user.user_id,user.money,date_format(user.verified_at),date_format(user.refused_at),date_format(user.created_at)
end
end


在index.html.erb中加入
<% url = request.url %>
<a href="<%= url.include?('?') ? url.gsub('?','.xls?') : (url.to_s << '.xls') %>">导出excel</a>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值