2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

ruby + win32oleでofficeファイルを印刷する

2
Posted at

ruby + Win32ole + officeを使用して、officeファイルを印刷する
(Word, Excel, PowerPointでそれぞれ、メソッド名が違うのはOffice仕様。。。)

試した環境

  • Windows2008
  • Office2010 standard
  • ruby2.0.0

Word

# -*- coding: utf-8 -*-
require 'win32ole'

wd = WIN32OLE.new('Word.Application')
wd.DisplayAlerts = false

# Wordファイルを開く
doc = wd.Documents.Open(:FileName => "C:\\hoge.doc")
wd.Options.PrintBackground = false

# プリンタ設定
wd.WordBASIC.FilePrintSetup(:Printer => "Printer1", :DoNotSetAsSysDefault => 1)

# 印刷
doc.PrintOut

# ファイルclose
doc.Close(false)
wd.Quit

Excel

# -*- coding: utf-8 -*-
require 'win32ole'

xl = WIN32OLE.new('Excel.Application')
xl.DisplayAlerts = false

# Excelファイルを開く
book = xl.Workbooks.Open(:Filename => "C:\\hoge.xls")

# 印刷
book.ActiveSheet.PrintOut(:ActivePrinter => "Printer1")

# ファイルclose
book.Close
xl.Workbooks.Close
xl.Quit

PowerPoint

# -*- coding: utf-8 -*-
require 'win32ole'

pp = WIN32OLE.new('PowerPoint.Application')
pp.Visible = true
pp.DisplayAlerts = false

# PowerPointファイルを開く
prs = pp.Presentations.Open(:FileName => "C:\\hoge.ppt", :WithWindow => false)
prs.PrintOptions.PrintInBackground = false

# プリンタ設定
prs.PrintOptions.ActivePrinter = "Printer1"

# 印刷
prs.PrintOut

# ファイルclose
prs.close
pp.Quit

注意点

  • 途中でエラーとかになり、close処理が行われないと、officeプロセス(WORD.exe, EXCEL.exe, POWERPNT.exe)が残る
  • ファイルを開く・印刷途中でエラー or 確認ダイアログが出たりすると、そこで処理が止まる(誰もボタンを押せないので)。また、DisplayAlerts = falseにしても、完全にメッセージの抑止はできない
2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?