在上篇的帖子里老猪提到了一个简单的把Rails Model对象
导出excel文件的插件
在
Rails项目中导入excel 导出excel 实用rails
解析excel
该插件易用性很好,就是像to_xml一样使用to_xls。然而,这个插件也有使用范围,比如,想要导出的excel有一些样式的时候就会多少有些问题。
那么下面的插件,在样式上稍微有些关注,使用上也同样吸取了to_xls的易用原则。
插件ekuseru
安装
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
Controller中使用
class ProductsController < ApplicationController
respond_to :html, :xls
def index
@products = Product.all
respond_with @products
end
...
end
样式的处理
是通过在app/views/products目录的index.xls.eku文件进行修改实现,就如同模板一样
其中__filename代表excel文件,而处理和整理excel样式和数据的操作可以使用我们上文介绍的spreadsheet
rails导出excel插件 spreadsheet的标准使用
官网的介绍也不错
模板样式如下
# 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) %>