这将在 Ruby 中完成。我已经提供了迄今为止我所尝试的内容。
我很好奇是否可以迭代 Excel 工作簿(因此它将是多个工作表)并基本上索引/记录所有内容所在的位置。假设我有一本 10 页的作业簿。我希望它抓取第一张工作表,记录该工作表名称,然后移动到第一个单元格并开始对该工作表上的数据建立索引(不确定单词是否正确)。它将记录第一个 (1,A) 的单元格位置以及其中的数据。我正在尝试将数据输出为 CSV 文件之类的格式:
我编写的一些代码基本上只是迭代工作簿中的每个工作表和每个单元格(删除空格)并获取其数据并放入 CSV...不存在工作表名称或单元格编号。我正在使用 roo 和 csv gem:
require 'rubygems'
require 'roo'
#Classes Used
class ArrayIterator
def initialize(array)
@array = array
@index = 0
end
def has_next?
@index < @array.length
end
def item
@array[@index]
end
def next_item
value = @array[@index]
@index += 1
value
end
end
#Open up files to compare
w1 = Excelx.new ( "C:/Ruby/myworkbook.xlsx" )
$values = Array.new
i = 0.to_i
# Continue until no worksheets left
num_sheets = w1.sheets().size
while (i < num_sheets)
puts "i is currently : #{i}"
puts "length of sheet array is : #{num_sheets}"
#Grab first sheet of each workbook
w1.default_sheet = w1.sheets[i]
1.upto(w1.last_row) do | row |
1.upto(w1.last_column) do | column |
string = w1.cell(row, column).to_s
if (string.strip.empty?)
puts "Whitespace!"
else
$values << string
end
end
end
i = i + 1.to_i
end
count = 0.to_i
CSV.open('C:/Ruby/results.csv', "w") do |csv|
csv << ['String']
i = ArrayIterator.new($values)
while i.has_next?
csv << [i.next_item]
count += 1
end
end
最佳答案
我冒昧地缩短了您的脚本,同时添加了对产生错误的空表的检查。
require 'roo'
w1 = Excelx.new ( "C:/Ruby193/test/roo/book1.xlsx" )
CSV.open("book1.csv", "w") do |csv|
w1.sheets.each do |sheet|
w1.default_sheet = sheet
if w1.first_row && w1.first_column
eval(w1.to_s).each do |index, value|
csv << [sheet, index, value]
end
end
end
end
其中给出了 book1.csv
Sheet1,"[1, 1]",a1
Sheet1,"[1, 2]",b1
Sheet1,"[2, 1]",a2
Sheet1,"[2, 2]",b2
Sheet2,"[1, 1]",aa1
Sheet2,"[1, 2]",bb1
Sheet2,"[2, 1]",aa2
Sheet2,"[2, 2]",bb2
关于ruby - 迭代 Excel 工作簿并对所有内容建立索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12061862/