https://github.com/asanghi/excel_rails
写道
excel_rails这是对spreadsheet插件的一个扩展。安装 excel_rails必须要安装spreadsheet
Gemfile
gem 'spreadsheet'
gem 'excel_rails'
写道
保存后执行
bundle install
写道
比如要打印UserController下面的index添加
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
写道
然后在对应视图的文件下面添加一个空白文件名为index.xls.rxls
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>