Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing to excel files in ruby using roo gem

I am parsing Excel and Excelx file using Roo gem. But I am not sure how to write in those files. set_value(row, column, text) method is not working.

Code

@oo = Excelx.new('tes.xlsx')
@oo.default_sheet = @oo.sheets.first

def return_column
  keywords = ["website", "url"]
  keywords.each do |keyword|
  1.upto(@oo.last_column) do |n|
  data = @oo.cell(1, n)
  return n if data.downcase=~/#{keyword}/i
end
end
end

def return_rows
  n = return_n
  2.upto(@oo.last_row) do |row|
  data = @oo.cell(row, n)
  stack << data 
 end
end

def appender
  @oo.set_value(1,11, "hey")
end

 appender

The Error Message I'm getting is

 /.rvm/gems/ruby-1.8.7-p352/gems/roo-1.10.1/lib/roo/generic_spreadsheet.rb:441:in `method_missing': private method `set_value' called for #<Excelx:0x101221f08> (NoMethodError)
from /Users/bhushan/.rvm/gems/ruby-1.8.7-p352/gems/roo-1.10.1/lib/roo/excelx.rb:168:in `method_missing'
from parser.rb:32:in `appender'
from parser.rb:35
like image 418
Bhushan Lodha Avatar asked Dec 13 '11 17:12

Bhushan Lodha


2 Answers

you can use set method

sheet.set(row, col, value)
like image 134
Mark Nguyen Avatar answered Sep 17 '22 06:09

Mark Nguyen


No answers here actually answer the question of how to do this with Roo, so I'll add the solution that I just tested in our app.

Roo recently added functionality for editing cells: https://github.com/roo-rb/roo/blob/master/lib/roo/csv.rb#L42

You can use it like such:

sheet.set_value(1, 5, 'TEST', nil) # to set the 1st row, 5th column to the string 'TEST'

Notes:

  • The last argument nil is not used in the function but has no default so it's required.
  • This is only added in version 2.7.0.
like image 43
Ryan Avatar answered Sep 18 '22 06:09

Ryan