另外一个Rails导出excel的例子

在上篇的帖子里[url=http://hlee.iteye.com]老猪[/url]提到了一个简单的把Rails Model对象导出excel文件的插件
[url=http://hlee.iteye.com/admin/blogs/749972]在Rails项目中导入excel 导出excel 实用rails解析excel[/url]

该插件易用性很好,就是像to_xml一样使用to_xls。然而,这个插件也有使用范围,比如,想要导出的excel有一些样式的时候就会多少有些问题。

那么下面的插件,在样式上稍微有些关注,使用上也同样吸取了to_xls的易用原则。

[size=large]插件ekuseru[/size]


[b]安装[/b]

Rails 3下

#Gemfile
gem "ekuseru"

bundle install

Rails 2下
cd vendor/plugins
git clone git://github.com/xinuc/ekuseru.git
git checkout remotes/origin/rails2 -b rails2


[b]Controller中使用
[/b]
  class ProductsController < ApplicationController
respond_to :html, :xls

def index
@products = Product.all
respond_with @products
end

...

end


[b]样式的处理[/b]

是通过在app/views/products目录的index.xls.eku文件进行修改实现,就如同模板一样

其中__filename代表excel文件,而处理和整理excel样式和数据的操作可以使用我们上文介绍的spreadsheet
[url=http://hlee.iteye.com/admin/blogs/356510]rails导出excel插件 spreadsheet的标准使用[/url]
[url=http://spreadsheet.rubyforge.org/GUIDE_txt.html]官网的介绍也不错[/url]

模板样式如下


# set the filename sent to the user with __filename variable
# this is optional, if you don't set it, the name will be like products.xls

__filename = "Products Catalog.xls"

# we get 'xls' variable which is a Workbook object
# then we can create some worksheet to work with, with create_worksheet method

sheet1 = xls.create_worksheet

# fill the [0, 0] cell

sheet1[0, 0] = "Products Catalog"

# Worksheet#row will return a Row object. We can modify it just like an Array.
# this code will return the second row and fill the cells.

sheet1.row(1).concat ["Name", "Price", "Stock", "Description"]

# we can access the instance variable we set in the controller, just like
# in erb template

@products.each_with_index do |p, i|
sheet1.update_row i+2, p.name, p.price, p.stock, p.description
end

# we can add some formatting using Spreadsheet::Format object

title_format = Spreadsheet::Format.new(:color => :blue, :weight => :bold, :size => 18)
sheet1.row(0).set_format(0, title_format)

bold = Spreadsheet::Format.new(:weight => :bold)
sheet1.row(1).default_format = bold


最后,导出的接口

<%= link_to 'Download as Excel', products_path(:format => :xls) %>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值