ruby parseexecel gem - array not implemented - ruby

I am trying to work with two worksheets at the same time.
So I have code
require 'parseexcel'
#Open the excel file passed in from the commandline
workbook = Spreadsheet::ParseExcel.parse(ARGV[0])
workbook2 = Spreadsheet::ParseExcel.parse(ARGV[1])
#Get the first worksheet
worksheet = workbook.worksheet(0)
worksheet2 = workbook2.worksheet(0)
However, when I run this code I get an error: array is not implemented
This error goes away when I comment out line:
workbook2 = Spreadsheet::ParseExcel.parse(ARGV[1])
Why is this happeneing?
Way I am running script is: ruby -rubygems traverse.rb excel.xls so.xls

i fixed it by copy pasting so.xls in excel.xls as a different workbook. then just accessed it by workbook.worksheet(1) that worked

Related

How to create, read and transform an XML file with Ruby

I am downloading an XML record from Musicbrainz.org, applying an XSLT transformation and outputting a new and different XML record.
I am running into one issue that I wonder if it is a limitation with my approach, XSLT transformations or applying Ruby to text.
I download the record:
require 'open-uri'
mb_metadata = open('http://musicbrainz.org/ws/2/release/?query=barcode:744861082927', 'User-Agent' => 'MarcBrainz marc4brainz#gmail.com').read
File.open('mb_record.xml', 'w').write(mb_metadata)
This works fine.
Then I want to transform that record. First I tried using Nokogiri:
# mb_metadata to transformed record
mb_record = Nokogiri::XML(File.read('mb_record.xml'))
#if we have the xslt document locally this introduces it
template = Nokogiri::XSLT(File.read('mb_to_marc.xsl'))
# this transforms the input document with the template.xslt
puts template.transform(mb_record)
If I run this on its own it works, however if I download the record and then run this it doesn't, it produces a transformed record which just contains some inserts, no element from the original XML file is transformed.
So I thought this might be an issue with Nokogiri and then I tried using the Ruby/XSLT gem:
xslt = XML::XSLT.new()
xslt.xml = 'mb_record.xml'
xslt.xsl = 'mb_to_marc.xsl'
out = xslt.serve()
print out;
Again, if I'm running this on a local file it works, but if I download it and try to transform it it doesn't work - it produces the following error:
xslt.xml = 'mb_record.xml'
Both methods work fine if I just run them on a file which has been downloaded already.
So what's the issue? Is it a naming problem, an XSLT issue, or something else?
Here's the whole script:
#!/usr/bin/env ruby
# encoding: UTF-8
require 'rubygems' if RUBY_VERSION >= '1.9'
require 'pathname'
require 'httpclient'
require 'xml/xslt'
require 'nokogiri'
require 'open-uri'
# DOWNLOAD RECORD FROM MusicBrainz.org - this works
mb_metadata = open('http://musicbrainz.org/ws/2/release/?query=barcode:744861082927', 'User-Agent' => 'MarcBrainz marc4brainz#gmail.com').read
#puts record
File.open('mb_record.xml', 'w').write(mb_metadata)
# mb_metadata to transformed record - this works on a saved file but not if the file is created earlier in this file .
#
#mb_record = Nokogiri::XML(File.read('mb_record.xml'))
#if we have the xslt document locally this introduces it
#template = Nokogiri::XSLT(File.read('mb_to_marc.xsl'))
# this is supposed to transform the input document with the template.xslt
#puts template.transform(mb_record)
# TRYING ANOTHER TACK
# This works if acting on a saved file. i.e. if I comment out the nokogiri lines above and just run the lines below - to 'print out' the xml is correctly transfored by the xslt to produce more xml.
# I added 'sleep 3' to see if that would help but it doesn't make a difference.
xslt = XML::XSLT.new()
xslt.xml = 'mb_record.xml'
xslt.xsl = 'mb_to_marc.xsl'
out = xslt.serve()
print out;
File.open('mb_record.xml', 'w').write(mb_metadata)
is better written as
File.write('mb_record.xml', mb_metadata)
The first will result in a file that hasn't been closed, and possibly not flushed to the disk, which can mean the file has no contents, or only partial contents.
The second writes the file and immediately flushes and closes it.

My gem cannot see a dictionary text file, I cannot get the path

I wrote an implementation of the hangman game. (It is played on the terminal). The game is working fine but I usually have some problems getting my program to open a dictionary txt file from where the word will be generated. Below is my code for generating the word
def word_generator(min, max)
words = File.open("../dictionary.txt"), "r").readlines.map!(&:chomp)
level_words = words.select { |i| i.length >= min && i.length <= max }
random_index = rand(level_words.length)
#game_word = level_words[random_index]
end
This approach works fine when I play my game locally and the dictionary text file is just one directory level away from my ruby file. Here is the problem:
When I package the project as a gem, and install it. It will throw this error in initialize': No such file or directory # rb_sysopen /Users/andeladev/Desktop/paitin_hangman/bin/dictionary.txt (Errno::ENOENT). It will only run fine when I put the text file in the present working directory of the terminal.
How do I go about writing the path in the argument passed to File.open that will tell the program to look for the file in the gem path rather than the present working directory.
Try this:
file_name = File.join(File.dirname(File.expand_path(__FILE__)), '../dictionary.txt')
words = File.open(file_name, "r").readlines.map!(&:chomp)

Using `gets` for file path [duplicate]

This question already has answers here:
Ruby: String Comparison Issues
(5 answers)
Closed 3 years ago.
I'm writing a script to edit an excel file. I'm testing if it collects information from a user.
require 'rubygems'
require 'win32ole'
print "filpath?"
$filepath = $stdin.gets
print "sheet?"
$sheetname = $stdin.gets
excel = WIN32OLE.new('Excel.Application')
excel.visible = true
workbook = excel.workbooks.Open($filepath)
worksheet = workbook.Worksheets($sheetname)
worksheet.Cells(2,2).Value = 10
workbook.saved = true
workbook.Save
excel.ActiveWorkbook.Close(0)
excel.Quit()
When I put my file path in the script directly, it works fine. It can look up the excel file and edit it normally. However, when I collect it from a gets statement, it gives me this error message:
test.rb:20:in `method_missing': (in OLE method `Open': ) (WIN32OLERuntimeError)
OLE error code:800A03EC in Microsoft Excel
Sorry, we couldn't find C:\filename.xlsx
. Is it possible it was moved, renamed or deleted?
HRESULT error code:0x80020009
Exception occurred.
from test.rb:20:in `<main>'
Not sure what is happening. I would love any help.
The end line character is appended to the file name when you receive it with gets, but probably your file is not named as such. Add .chomp after gets. It is also better to check the existence and the accessibility of the file before passing it to win32ole.

RubyZip Unzipping .docx, modifying, and zipping back up throws Errno::EACCESS error

So, I'm using Nokogiri and Rubyzip to unzip a .docx file, modify the word/docoument.xml file in it (in this case just change every element wrapped in to say "Dreams!"), and then zip it back up.
require 'nokogiri'
require 'zip'
zip = Zip::File.open("apple.docx")
doc = zip.find_entry("word/document.xml")
xml = Nokogiri::XML.parse(doc.get_input_stream)
inputs = xml.root.xpath("//w:t")
inputs.each{|element| element.content = "DREAMS!"}
zip.get_output_stream("word/document.xml", "w") {|f| f.write(xml.to_s)}
zip.close
Running the code through IRB line by line works perfectly and makes the changes to the .docx file as I needed, but if I run the script from the command line
ruby xmltodoc.rb
I receive the following error:
C:/Ruby193/lib/ruby/gems/1.9.1/gems/rubyzip-1.1.7/lib/zip/file.rb:416:in `rename': Permission denied - (C:/Users/Bane/De
sktop/apple.docx20150326-6016-k9ff1n, apple.docx) (Errno::EACCES)
from C:/Ruby193/lib/ruby/gems/1.9.1/gems/rubyzip-1.1.7/lib/zip/file.rb:416:in `on_success_replace'
from C:/Ruby193/lib/ruby/gems/1.9.1/gems/rubyzip-1.1.7/lib/zip/file.rb:308:in `commit'
from C:/Ruby193/lib/ruby/gems/1.9.1/gems/rubyzip-1.1.7/lib/zip/file.rb:332:in `close'
from ./xmltodoc.rb:15:in `<main>'
All users on my computer have all permissions for that .docx file. The file also doesn't have any special settings--just a new file with a paragraph. This error only shows up on Windows, but the script works perfectly on Mac and Ubuntu. Running Powershell as Admin throws the same error. Any ideas?
On my Windows 7 system the following works.
require 'nokogiri'
require 'zip'
Zip::File.open("#{File.dirname(__FILE__)}/apple.docx") do |zipfile|
doc = zipfile.read("word/document.xml")
xml = Nokogiri::XML.parse(doc)
inputs = xml.root.xpath("//w:t")
inputs.each{|element| element.content = "DREAMS!"}
zipfile.get_output_stream("word/document.xml") {|f| f.write(xml.to_s)}
end
Instead you also could use the gem docx, here is an example, the names of the bookmarks are in dutch because, well that's the language my MS Office is in.
require 'docx'
# Create a Docx::Document object for our existing docx file
doc = Docx::Document.open('C:\Users\Gebruiker\test.docx'.gsub(/\\/,'/'))
# Insert a single line of text after one of our bookmarks
# p doc.bookmarks['bladwijzer1'].methods
doc.bookmarks['bladwijzer1'].insert_text_after("Hello world.")
# Insert multiple lines of text at our bookmark
doc.bookmarks['bladwijzer3'].insert_multiple_lines(['Hello', 'World', 'foo'])
# Save document to specified path
doc.save('example-edited.docx')

Can't read from xlsx file with rubyXL

I'm trying to work with excel files(xlsx) in ruby using rubyXl. I have no problem writing but can't get to output the content of a cell.
require 'rubyXL'
workbook = RubyXL::Workbook.new
workbook.worksheets[0].add_cell(5,5,"test")
workbook.write("file3.xlsx")
getcell = RubyXL::Parser.parse("file3.xlsx")
print getcell[0][5][5]
When I run it in cmd I just get this and it changes every time I run the code.
D:\KEA\1.semester\Exams\IT exam>ruby test.rb
#<RubyXL::Cell:0x2e4a600>
SOLUTION:
After reading a few more times I found the answer in
http://rubydoc.info/gems/rubyXL/1.1.12/RubyXL/Cell
It should have been
print getcell[0][5][5].value
After reading a few more times I found the answer in
http://rubydoc.info/gems/rubyXL/1.1.12/RubyXL/Cell
It should have been
print getcell[0][5][5].value

Resources