0

我有一个数组数组,例如:

arr_all = [arr_1, arr_2, arr_3, arr_r]

在哪里:

arr_1 = [2015-08-19 17:30:24 -0700, 2015-08-19 17:30:34 -0700, 2015-08-19 17:30:55 -0700]
arr_2 = ...
arr_3 = ...

我有一个文件要修改。我知道如何将数组添加为一行,但我需要帮助将每个数组插入@@ar_data为列。我找到Row要插入数据的,然后我想arr_1在单元格中插入(next_empty_row, B),然后arr_2(next_empty_row, C),等等。请指教。填充数据的行数是每个数组的大小。arr_1, arr_2,arr_3大小为3

def performance_report
  Spreadsheet.client_encoding = 'UTF-8'
  f = "PerformanceTest_S.xls"
  if File.exist? (f)
    # Open the previously created Workbook
    book = Spreadsheet.open(f)
    sheet_1_row_index = book.worksheet(0).last_row_index + 1
    sheet_2_row_index = book.worksheet(1).last_row_index + 1
    # Indicate the row index to the user
    print "Inserting new row at index: #{sheet_2_row_index}\n"
    # Insert array as column - I need help with the below code to insert data in arr_data which is array of arrays. 
    column = 1
    row
    @@ar_data.each do |time|
      len = time.size
      book.worksheet(0).cell(sheet_1_row_index, )
      book.worksheet(0).Column.size
    end
    # This insert row is for worksheet 2 and works fine.
    book.worksheet(1).insert_row(sheet_2_row_index, @@ar_calc)
    # Delete the file so that it can be re-written
    File.delete(f)
    # puts @@ar_calc
    # Write out the Workbook again
    book.write(f)
4

2 回答 2

0

我不太确定你试图完成什么。这是一个如何将数组写入文件末尾的示例。

require 'spreadsheet'

arrays = [
['Text 1','Text 2','Text 3'],
['Text 4','Text 5','Text 6'],
['Text 7','Text 8','Text 9']]

f = '/your/file/path.xls'
Spreadsheet.client_encoding = 'UTF-8'
if File.exist? f
    book = Spreadsheet.open(f)
    sheet = book.worksheet(0)

    lastRow = sheet.last_row_index + 1
    arrays.each_with_index do |row, rowNum|
          row.each_with_index do |cell, cellNum|
              sheet[ rowNum + lastRow, cellNum ] = cell
          end
    end
    File.delete f
    book.write f
end
于 2015-08-21T00:12:07.760 回答
0

我什至不知道您在说什么,但您可能应该做的是将 xls 转换为 csvs(每张纸一个),然后像这样解析它。我将使用哈希使其与平台无关(但通常我只是使用 rails 直接将电子表格数据添加到数据库中):

require 'csv' #not necessary in newer versions of ruby
rows = CSV.open("filename.csv").read
column_names = rows.shift
records = []
rows.each do |row|
  this_record = {}
  column_names.each_with_index do |col, i|
    this_record[col] = row[i]
  end
  records << this_record
end

如果您不想手动将每张工作表转换为 CSV,您可以使用电子表格 gem 或类似的东西将每张工作表转换为数组数组,这基本上就是一个 CSV 文件。

在 ruby​​ 中,Hashes 从Enumerable类继承,就像 Arrays 一样。因此,要将您的散列转换为元组数组(两个元素数组,每个数组都有键和值),您只需要这样做:

records = records.map(&:to_a)

但这甚至不是必需的,您可以直接迭代并同时分配哈希,就像使用数组数组一样

records.each_with_index do |hsh, i|
  hsh.each do |k,v|
    puts "record #{i}: #{k}='#{v}'"
  end
end
于 2015-08-20T23:39:21.387 回答