使用spreadsheet操作Excel
这可能是Ruby读取Excel最好的gem了。还有一种方法是调用win32ole,不能跨平台。
一个陷阱:spreadsheet不能精确识别数字单元格类型,所有数字都识别成Float
读取Excel
1 |
#coding: utf-8 |
2 |
require 'spreadsheet' |
3 |
4 |
#r表示以只读方式打开,如果要写写 |
5 |
book = Spreadsheet.open( '~/read.xls' , 'r' ) |
6 |
#选择第一个表格 |
7 |
sheet1 = book.worksheet( 0 ) |
8 |
sheet1. each do |row| |
9 |
row. each do |cell| |
10 |
puts cell |
11 |
# 如果是Float类型,转为字符串并打印 |
12 |
puts cell.to_i.to_s if cell.is_a?(Float) |
13 |
end |
14 |
end |
写Excel
1 |
#coding: utf-8 |
2 |
require 'spreadsheet' |
3 |
4 |
book = Spreadsheet::Workbook. new |
5 |
sheet1 = book.create_worksheet :name => 'My Worksheet' |
6 |
#给第1行的前三个单元格赋值 |
7 |
sheet1.row( 0 ).concat %w{Name Country Acknowlegement} |
8 |
#给第2行第1格赋值 |
9 |
sheet1[ 1 , 0 ] = 'Rubyer' |
10 |
row = sheet1.row( 1 ) |
11 |
#向后续单元格添加 |
12 |
row.push 'Ruby Excel Writer' |
13 |
14 |
#设置行高 |
15 |
sheet1.row( 0 ).height = 18 |
16 |
#设置样式 |
17 |
format = Spreadsheet::Format. new :color => :blue , |
18 |
:weight => :bold , |
19 |
:size => 18 |
20 |
sheet1.row( 0 ).default_format = format |
21 |
bold = Spreadsheet::Format. new :weight => :bold |
22 |
4 .times do |x| sheet1.row(x + 1 ).set_format( 0 , bold) end |
23 |
#保存 |
24 |
book.write '~/write.xls' |
参考资料:
http://spreadsheet.rubyforge.org
http://spreadsheet.rubyforge.org/file.GUIDE.html