[ruby + excel] Precautions for Save As

In ruby, you can operate Excel by using win32ole. I got an error at SaveAs, so make a note of it. It was an error like method_missing: (in OLE method'saveas') (WIN32OLERuntimeError).

Conclusion

When saving in the specified directory --Make it an absolute path. --The path delimiter is \ instead of /.

require 'win32ole'

app = WIN32OLE.new('Excel.Application')
book = app.workbooks.add
out_path = File.expand_path('test.xlsx').gsub('/', '\\')
book.saveas filename: out_path
book.close savechanges: false
app.quit

About the path specified by SaveAs

  1. Relative paths are based on the locals that Excel has.
  2. Set the path delimiter to \ instead of /.
  3. Named arguments are specified by symbols.

1. Current that Excel has

Relative paths are available in ruby. Relative paths can be used in Excel, but the location pointed to by "current" is the local folder set in Excel. This is the location described in the optional "Default local file storage location". So, I will make it an absolute path to make the place where ruby is running current.

out_path = File.expand_path('test.xlsx')

2. The path delimiter is \ instead of /.

In ruby path, / (slash) is used to separate the hierarchy. Apparently it couldn't be saved as it is, so replace the delimiter with \ (backslash).

out_path = File.expand_path('test.xlsx').gsub('/', '\\')

3. Specifying named arguments

Named arguments can be specified by symbols. In VBA, ": =" is used, but it is written as follows.

workbook.saveas filename: path

It has not been verified why it can be done. Because you are passing arguments as hashes?

Digression

It seems to be the basics of ruby,

p out_path

In, the string is enclosed in "" and \ is escaped as \\. (I want to make it one, not \\!, And do various things for several hours ...) It's just a prompt display issue, and there is actually only one .

puts out_path

I should have done it.

Since it is a ruby beginner, there may be a wrong description. I would appreciate it if you could point out in the comments.

Recommended Posts

[ruby + excel] Precautions for Save As
abbreviation for ruby method
Ruby Learning # 23 For Loops
Scraping for beginners (Ruby)
Save Java PDF in Excel
[Java] Precautions for type conversion
Save Java HTML as PDF
[Ruby] What is `!!` used for?
Precautions for updating Realm object