Ruby写入Excel文件 插件方法

阅读更多

 spreadsheet插件(主要是excel生成写入数据)

 

安装方式:gem install spreadsheet
Excel文件生成写入数据实例:
require ‘rubygems’
require ‘spreadsheet/excel’
#先加载spreadsheet类库,然后,指定编码接着,就可以创建一个Workbook了
book = Spreadsheet::Workbook.new
#创建表单:
sheet1 = book.create_worksheet
sheet1.name = ‘My First Worksheet’
#或直接指定名字创建表单:
sheet2 = book.create_worksheet :name => ‘My Second Worksheet’
那么,这时我们可以采用如下方式加载数据到表单Worksheet#[]=,
Worksheet#update_row,
或者直接给一个指定单元格复制
sheet1.row(0).concat %w{Name Country Acknowlegement}
sheet1[1,0] = ‘Japan’
row = sheet1.row(1)
row.push ‘Creator of Ruby’
row.unshift ‘Yukihiro Matsumoto’
sheet1.row(2).replace [ 'Daniel J. Berger', 'U.S.A.',
'Author of original code for Spreadsheet::Excel' ]
sheet1.row(3).push ‘Charles Lowe’, ‘Author of the ruby-ole Library’
sheet1.row(3).insert 1, ‘Unknown’
sheet1.update_row 4, ‘Hannes Wyss’, ‘Switzerland’, ‘Author’
#对输出格式做处理
sheet1.row(0).height = 18
format = Spreadsheet::Format.new :color => :blue,
:weight => :bold,
:size => 18
sheet1.row(0).default_format = format
bold = Spreadsheet::Format.new :weight => :bold
4.times do |x| sheet1.row(x + 1).set_format(0, bold) end
#保存excel文件
book.write ‘excel-file.xls’

你可能感兴趣的:(ruby,rails,excel,spreadsheet)