I've got this piece of code that works for Excel.
require 'win32ole'
excel = WIN32OLE.new('Excel.Application')
excel.visible = true
workbook = excel.Workbooks.Open('c:\file.xls');
But I have trouble getting the same thing done with for PowerPoint; This piece of code:
require 'win32ole'
ppt = WIN32OLE.new('Powerpoint.Application')
ppt.visible = true
presentation = ppt.Presentations.Open('c:\file.pptx');
Generates this error:
filename.rb in `method_missing': (in OLE method `Open': ) (WIN32OLERuntimeError)
OLE error code:80004005 in <Unknown>
<No Description>
HRESULT error code:0x80020009
Exception occurred.
Microsoft Support site says that the only required parameter is the filename.
I've found an ugly workaround:
require 'win32ole'
require 'fileutils'
ppt = WIN32OLE.new('PowerPoint.Application')
ppt.visible = true
system "start c:/presentation.ppt"
puts ppt.ActivePresentation.Slides.Count()
ppt.ActivePresentation.Slides(2).Export("filename.jpg", ".jpg", 1024,768)
ppt.ActivePresentation.Close();
I put a 3 second wait and it fixes the problem
I got same error and adding ppt.visible = true was good enough for me.
Try using Add instead of Open or Connect
for example:
presentation = ppt.Presentations.Add('c:\file.pptx');
Related
I'm learning my first coding language (Ruby) and I'm having trouble crawling a link. I'm trying to grab image-URLs and eventually going to save to a CSV. I've looked at many tutorials and a lot of question on here, but none seem to solve my problem.
The problem appears to be in the final line (Line 19).
Error Message: 19:in `[]': no implicit conversion of String into Integer
Any help would be appreciated!
require 'rubygems'
require 'nokogiri'
require 'open-uri'
PAGE_URL = "http://www.bestbuy.com/site/samsung-showcase-27-8-cu-ft-french-door-refrigerator-with-thru-the-door-ice-and-water-stainless-steel/5236091.p?id=1219116001631&skuId=5236091"
page = Nokogiri::HTML(open(PAGE_URL))
link_extract = page.css('div#pdp-content div.image-gallery-main-slide a img[data-index="1"]')
puts link_extract[0]['src']
It looks like a large part of this page is built with javascript.
If you look at the raw html you get you won't see the content you're looking for since youre essentially doing a curl to get the data.
Soo how should you proceed? I'd say you have two options:
The easiest way to get the data you want, is to get the json they're using at #pdp-model-data
Use some kind of web driver that works well with javascript. I tried phantomjs but it looks like that page contains some invalid syntax and it's only pulling the first image.
e.g.
require 'capybara/poltergeist'
url = "http://www.bestbuy.com/site/samsung-showcase-27-8-cu-ft-french-door-refrigerator-with-thru-the-door-ice-and-water-stainless-steel/5236091.p?id=1219116001631&skuId=5236091"
session = Capybara::Session.new(:poltergeist)
session.visit(url)
page = Nokogiri::HTML::DocumentFragment.parse(session.html)(session.html)
page.search("#pdp-content div.image-gallery-main-slide a img")
# => [#<Nokogiri::XML::Element:0x3ffe438d4100 name="img" attributes=[#<Nokogiri::XML::Attr:0x3ffe438d409c name="src" value="http://pisces.bbystatic.com/image2/BestBuy_US/images/products/5236/5236091_sa.jpg;canvasHeight=500;canvasWidth=500">, #<Nokogiri::XML::Attr:0x3ffe438d4088 name="alt" value="Samsung - Showcase 27.8 Cu. Ft. French Door Refrigerator with Thru-the-Door Ice and Water - Stainless-Steel - Larger Front">, #<Nokogiri::XML::Attr:0x3ffe438d4074 name="width" value="500">, #<Nokogiri::XML::Attr:0x3ffe438d4060 name="height" value="500">, #<Nokogiri::XML::Attr:0x3ffe438d404c name="data-index" value="0">, #<Nokogiri::XML::Attr:0x3ffe438d4038 name="style" value="display: block; ">]>]
edit #1:
require 'nokogiri'
require 'open-uri'
require 'json'
url = "http://www.bestbuy.com/site/samsung-showcase-27-8-cu-ft-french-door-refrigerator-with-thru-the-door-ice-and-water-stainless-steel/5236091.p?id=1219116001631&skuId=5236091"
page = Nokogiri::HTML(open(url))
json = page.css('#pdp-model-data').attribute('data-gallery-images').value
gallery = JSON.parse(json, symbolize_names: true)
puts gallery[1][:url]
#=> "http://img.bbystatic.com/BestBuy_US/images/products/5236/5236091cv1a.jpg"
I've made a small CLI script in ruby to manage a small shop for a friend, but then he wanted me to make a GUI for him, so I looked around and found shoes4.
So, I went and download it, created a small test, and run:
./bin/shoes -p swt:jar ./path/to/app.rb
and left it to create the package, then I got a warning from system that I'm running low on disc space, so I went to check the jar file, and it was over 1.5GB and still not done packaging... and the code is very small and basic:
require 'yaml'
Shoes.app do
button "Add client" do
filename = ask_open_file
para File.read(filename)
clients = YAML.load_file(filename)
id = clients[clients.length - 1][0].to_i + 1
name = ask("Enter the client's full name: ")
items = ask("Enter list of items.")
patients[id] = ["ID = "+ id.to_s,"Name = "+ pname,"list of items:\n"+ items]
File.open(filename, 'w') { |f| YAML.dump(clients, f) }
alert ("Added new patient.")
end
button "Exit" do
exit()
end
end
any idea why this small app is more than 1.5GB?? or did I try to package it wrong way??
The packager will include everything in the directory of your shoes script and below.
I have a script, VBS or Ruby, that saves a Word document as 'Filtered HTML', but the encoding parameter is ignored. The HTML file is always encoded in Windows-1252. I'm using Word 2007 SP3 on Windows 7 SP1.
Ruby Example:
require 'win32ole'
word = WIN32OLE.new('Word.Application')
word.visible = false
word_document = word.documents.open('C:\whatever.doc')
word_document.saveas({'FileName' => 'C:\whatever.html', 'FileFormat' => 10, 'Encoding' => 65001})
word_document.close()
word.quit
VBS Example:
Option Explicit
Dim MyWord
Dim MyDoc
Set MyWord = CreateObject("Word.Application")
MyWord.Visible = False
Set MyDoc = MyWord.Documents.Open("C:\whatever.doc")
MyDoc.SaveAs "C:\whatever2.html", 10, , , , , , , , , , 65001
MyDoc.Close
MyWord.Quit
Set MyDoc = Nothing
Set MyWord = Nothing
Documentation:
Document.SaveAs: http://msdn.microsoft.com/en-us/library/bb221597.aspx
msoEncoding values: http://msdn.microsoft.com/en-us/library/office/aa432511(v=office.12).aspx
Any suggestions, how to make Word save the HTML file in UTF-8?
Hi Bo Frederiksen and kardeiz,
I also encountered the problem of "Word Document.SaveAs ignores encoding" today in my "Word 2003 (11.8411.8202) SP3" version.
Luckily I managed to make msoEncodingUTF8(namely, 65001) work in VBA code. However, I have to change the Word document's settings first. Steps are:
1) From Word's 'Tools' menu, choose 'Options'.
2) Then click 'General'.
3) Press the 'Web Options' button.
4) In the popping-up 'Web Options' dialogue, click 'Encoding'.
5) You can find a combobox, now you can change the encoding, for example, from 'GB2312' to 'Unicode (UTF-8)'.
6) Save the changes and try to rerun the VBA code.
I hope my answer can help you. Below is my code.
Public Sub convert2html()
With ActiveDocument.WebOptions
.Encoding = msoEncodingUTF8
End With
ActiveDocument.SaveAs FileName:=ActiveDocument.Path & "\" & "file_name.html", FileFormat:=wdFormatFilteredHTML, Encoding:=msoEncodingUTF8
End Sub
Word can't do this as far as I know.
However, you could add the following lines to the end of your Ruby script
text_as_utf8 = File.read('C:\whatever.html').encode('UTF-8')
File.open('C:\whatever.html','wb') {|f| f.print text_as_utf8}
If you have an older version of Ruby, you may need to use Iconv. If you have special characters in 'C:\whatever.html', you'll want to look into your invalid/undefined replacement options.
You'll also probably want to update the charset in the HTML meta tag:
text_as_utf8.gsub!('charset=windows-1252', 'charset=UTF-8')
before you write to the file.
My solution was to open the HTML file using the same character set, as Word used to save it.
I also added a whitelist filter (Sanitize), to clean up the HTML. Further cleaning is done using Nokogiri, which Sanitize also rely on.
require 'sanitize'
# ... add some code converting a Word file to HTML.
# Post export cleanup.
html_file = File.open(html_file_name, "r:windows-1252:utf-8")
html = '<!DOCTYPE html>' + html_file.read()
html_document = Nokogiri::HTML::Document.parse(html)
Sanitize.new(Sanitize::Config::RESTRICTED).clean_node!(html_document)
html_document.css('html').first['lang'] = 'en-US'
html_document.css('meta[name="Generator"]').first.remove()
# ... add more cleaning up of Words HTML noise.
sanitized_html = html_document.to_html({:encoding => 'utf-8', :indent => 0})
# writing output to (new) file
sanitized_html_file_name = word_file_name.sub(/(.*)\..*$/, '\1.html')
File.open(sanitized_html_file_name, 'w:UTF-8') do |f|
f.write sanitized_html
end
HTML Sanitizer: https://github.com/rgrove/sanitize/
HTML parser and modifier: http://nokogiri.org/
In Word 2010 there is a new method, SaveAs2: http://msdn.microsoft.com/en-us/library/ff836084(v=office.14).aspx
I haven't tested SaveAs2, since I don't have Word 2010.
I want to upload files into "Share Documents" by ruby script.
I tried "savon" to link sparepoint but it can't succeed.
" WSDL = "http://xxx.xx.com/sites/OK/Shared%20Documents" " is right?
" client.request.basic_auth "user", "userpasd" "
And it show a error message
'request': Savon::Client#request requires at least one argument (ArgumentError)
How to fix it and how to link/upload/download file from sharepoint by ruby script?
Thanks a lot,
I was having this same problem and found the answer via google - https://groups.google.com/forum/#!msg/savonrb/gq90FDuu77s/H7ip3VNnt0MJ
The provided answer:
client = Savon::Client.new do
wsdl.document = File.expand_path('../../../lib/wsdl/MI_TESTConnection_OutHTTP.wsdl', __FILE__)
http.auth.basic "user", "password"
end
This is the actual code that worked for me:
client = Savon.client("http://path.to.my/service.wsdl") do
http.auth.basic "user", "password"
end
Is it practical to call a VBScript function, such as VBScript's Chr(charcode), from Ruby using win32ole?
Background: While working out how to add some nicely formatted headers to an excel worksheet, I followed my standard operating procedure: record an excel macro and copy and paste the code.
VBScript:
ActiveWindow.View = xlPageLayoutView
With ActiveSheet.PageSetup
' Irrelevant options snipped
.CenterHeader = "&F" & Chr(10) & "&A"
' More irrelevant options snipped
End With
The following Ruby code
# workbook is an existing workbook object
worksheet = workbook.Worksheets.Add
worksheet.PageSetup.CenterHeader = "&F \n &A"
works, but I had to look up the Chr(charcode) documentation to check it was the exact same thing. I tried doing
worksheet.PageSetup.CenterHeader = "&F" + workbook.Chr(10) + "&A"
but got
WIN32OLERuntimeError: unknown property or method: `Chr'
HRESULT error code:0x80020006
Unknown name.
from (irb):6:in `method_missing'
from (irb):6
from c:/Ruby19/bin/irb:12:in `<main>'
Is there any practical way to do the latter approach?
I wouldn't call a vbscript script for something that is easier done in Ruby but it is possible.
How you requested it:
require 'win32ole'
sc = WIN32OLE.new("ScriptControl")
sc.language="VBScript"
center_header = sc.eval('"&F" & Chr(10) & "&A"') #"&F\n&A"
and how you could do it in Ruby itself
"&F" + 10.chr + "&A" #"&F\n&A"
or
"&F\n&A" #"&F\n&A"
EDIT: For 64bit windows that wouldn't work any longer out of the box, you need to install a 64 bit dll that you can find at https://tablacus.github.io/scriptcontrol.html (The site is in japanese so translate the page in your browser)
how 'bout
worksheet.PageSetup.CenterHeader = "&F" + 10.chr + "&A"