我有一个数组数组,如:
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)
答案 0 :(得分: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,您可以使用Spreadsheet 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
答案 1 :(得分: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