遍历Excel工作簿并索引所有内容?

这将在Ruby中完成..我已经提供了迄今为止我所尝试的。

我很好奇,如果有可能迭代一个Excel工作簿(所以这将是多张),并基本上索引/logging一切都位于。 可以说我有一张10张工作簿。 我希望它抓住第一张纸,logging表名称,然后移动到第一个单元格,并开始索引(不知道是否正确的单词)该表上的数据。 它将logging第一个(1,A)的单元格位置以及其中的数据。 我正在尝试将数据输出为像CSV文件或类似的格式: 在这里输入图像说明

我写的一些代码基本上只是遍历工作簿中的每个工作表和单元格(删除空格),并抓取它的数据并放入一个CSV …没有表名或单元格号存在。 我正在使用roo和csvgem:

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