Create  Edit  Diff  FrontPage  Index  Search  Changes  Login

RubyScriptTemplate

目的

スクリプトを書くときの最初のテンプレートをいくつかメモ

スクリプトの実行

if $0 == __FILE__
  # 実行
end

ファイルを更新する

require 'fileutils'
require 'tempfile'

def update(name)
  tf = Tempfile.new("foo")
  File.open(name, 'r').each do |line|
    #
    tf.puts(line)
  end
  tf.close
  File.rename(name, name + '.bak')
  FileUtils.copy_file(tf.path, name)
end

Excelシートを巡回する

require 'win32ole'

def read_sheets(file)
  begin
    excel = WIN32OLE.new('Excel.Application')
    excel.displayAlerts = false
    excel.visible = true if $DEBUG
    book = excel.Workbooks.Open(file)

    excel.ScreenUpdating = false
    1.upto(excel.ActiveWorkbook.Sheets.Count) do |num|

      do_something(excel.Sheets.item(num))

    end
    excel.ScreenUpdating = true
    book.close(false)
    excel.Quit

  rescue RuntimeError => e
    p e.backtrace
    STDERR.puts e.message
  end
end

read_sheets(File.expand_path(file))

新規ブック

excel = WIN32OLE.new('Excel.Application')
excel.visible = true
book = excel.WorkBooks.Add
sheet = book.WorkSheets.Item(1)
sheet.Name = 'tab name'

行と列の入れ替え

a = [['A1', 'A2', 'A3', 'A4'], ['B1', 'B2', 'B3', 'B4']]
sheet.Range(sheet.Cells(1, 1), sheet.Cells(4, 2)).Value = a.transpose
#または
sheet.Range('A1:B4').Value = a.transpose

シートの内容を配列化

def sheet_to_a(sheet)
  a = []
  cols = sheet.usedRange.Columns.Count
  1.upto(sheet.usedRange.Rows.Count) do |rc|
    c = []
    1.upto(cols) do |cc|
      c << sheet.cells(rc, cc).value
    end
    a << c
  end
  a
end

ログ付きで子プロセスを実行

def system_with_log(cmd, path)
  out = STDOUT.dup
  STDOUT.reopen path, 'w'
  err = STDERR.dup
  STDERR.reopen path, 'a'
  ret = system cmd
  STDOUT.flush
  STDOUT.reopen out
  STDERR.flush
  STDERR.reopen err
  ret
end
Last modified:2014/01/15 07:35:57
Keyword(s):
References: