8
13

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を使ったExcelサンプルプログラム

Last updated at Posted at 2015-12-06

別に目新しいものは何もないが、自分用のRubyでExcelを使うために作業メモで、Windows環境でのwin32oleを使ったExcelアクセスサンプルプログラム。
ちなみにQiitaへの初めての投稿です。

#参考にさせて頂いたURL

#サンプルプログラム

excel_test.rb
#!/usr/bin/env ruby
# -*- coding: utf-8 -*-
STDOUT.sync = true

require 'win32ole'

# Excel VBA定数のロード
module Excel; end

def init_excel()
  # Excelオブジェクト生成
  excel = WIN32OLE.new('Excel.Application')
  excel.visible = true
  # 上書きメッセージを抑制
  excel.displayAlerts = false

  WIN32OLE.const_load(excel, Excel)

  return excel
end

def create_excel(excel, file)
  # 新規ブックを作成
  workbook = excel.workbooks.add

  # 先頭シートを選択
  sheet = workbook.sheets[1]

  # 九九の表を作成
  (1..9).each do |i|
    sheet.rows[1].columns[i + 1] = i
    sheet.rows[i + 1].columns[1] = i
  end
  sheet.range('B2:J10').value = '=$A2*B$1'

  # ボーダーライン
  sheet.range('A1:J10').borders.lineStyle = Excel::XlContinuous

  # 表のヘッダー
  range = sheet.range('A1:A10,B1:J1')
  # 背景色
  range.interior.themeColor = Excel::XlThemeColorAccent1
  # フォント
  range.font.themeColor = Excel::XlThemeColorDark1
  range.font.bold = true

  # 列の幅
  sheet.columns('A:J').columnWidth = 6

  # 保存
  workbook.saveAs(file)

  # ファイルを閉じる
  workbook.close
end

def read_excel(excel, file, sheet_num = 1)
  book = excel.Workbooks.Open(file)
  sheet = book.Worksheets(sheet_num)

  # 列ごとに処理
  sheet.UsedRange.Rows.each do |row|
    # セルごとに処理
    row.Columns.each do |cell|
      puts cell.value
    end
  end
end

def main()
  # OLE32用FileSystemObject生成
  fso = WIN32OLE.new('Scripting.FileSystemObject')
  file = fso.GetAbsolutePathName('./sample.xlsx')

  excel = init_excel()

  create_excel(excel, file)
  read_excel(excel, file)

  excel.quit()
end

main()
8
13
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
8
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?