Ruby读取Excel文件的两种方法

来源:互联网 发布:anaconda mac 安装 编辑:程序博客网 时间:2024/06/06 20:08
用Ruby读取Excel文件的两种重要方式
1. 通常做法,查阅微软提供的API了,需要包含win32, 在ruby前加入,require ‘win32ole’
例如:
require ‘win32ole’
myexcel = WIN32OLE.new(“excel.application”)
myexcel.visible=true
mywbk = myexcel.Workbooks.Add()
mywst= mywbk.Worksheets(1)
mywst.Range(‘A1:D1′).value =['1','2','3','4']
将['1','2','3','4']写入EXCEL的’A1:D1′区域
或 使用纯ruby 读写excel
@file_task_name =”e:/test.xls”
@fo=File.open(@file_task_name,”r”)
# def total_lines@lines = 0@fo.each_with_index {|@item,@lines|}puts @lines+1@lines= @lines+1File.open(@file_task_name) do |file|#file.each_line{|line| puts line}file.close();
2. 使用操作excel的第三方工具(推荐):
Parseexcel插件(主要是excel读取)
安装方式:gem install parseexcel
读取excel文件实例:
require ‘rubygems’
require ‘parseexcel’
#得到第一个表单
workbook = Spreadsheet::ParseExcel.parse(“C:/test.xls”)
#遍历行
worksheet = workbook.worksheet(0)
#遍历该行非空单元格
j=0  # initialize row
worksheet.each { |row|     i=0    if row != nil
#取得单元格内容为string类型
row.each { |cell|      if cell != nil
# 若excel里面含有中文推荐使用‘GB2312′;若为英文字符一般采用默认字符集’latin1′
contents = cell.to_s(‘GB2312′)
puts “Row: #{j} Cell: #{i} #{contents}”
end
i = i+1
}
j = j +1
end
}
备注:
cell.to_s(‘latin1′) #读取字符串
cell.to_i           #读取int值
cell.date           #读取一个时间值
cell = row.at(3)    #读取特定值
0 0
原创粉丝点击