Home > Software engineering >  RubyXL export array to xlsx file
RubyXL export array to xlsx file

Time:08-10

I have an array of data which I want to export to xlsx file. An array size depends on input data so the array size will change and using add_cell is problematic. Is there any way to add rows with data to workbook?

CodePudding user response:

I did something like this

require 'rubyXL'

new_array = [["some", "data", "here"], ["another", "data", "here"]]

workbook = RubyXL:workbook.new
worksheet = workbook[0]

new_array.each_with_index do |x, index|
   col = *(0..(x.size - 1))
   col.each do |i|
     worksheet.add_cell(index, i, "#{x[i]}")
   end
end

workbook.write("/path/to/file/file.xlsx")

I hope it will help someone with similar issue.

CodePudding user response:

Building on your self-answer: I think you have made life much more difficult for yourself by using cryptic variable names (new_array, x, index, col and i). I had to re-read your code multiple times to make sense of it, which is never a good sign.

Here I have re-written it with clearer variable names, and as you see the logic can actually be simplified a bit too! (This wasn't so obvious when the variable names were all mysterious.)

require 'rubyXL'

spreadsheet_data = [["some", "data", "here"], ["another", "data", "here"]]

workbook = RubyXL:workbook.new
worksheet = workbook[0]

spreadsheet_data.each_with_index do |spreadsheet_row, row_number|
   spreadsheet_row.each_with_index do |spreadsheet_value, column_number|
     worksheet.add_cell(row_number, column_number, spreadsheet_value)
   end
end

workbook.write("/path/to/file/file.xlsx")
  • Related