2016年6月10日金曜日

Python | 複数の画像ファイルをWordの表に貼りつける方法

Microsoft Wordの表の1セルに1コマずつ、複数(多数)の画像ファイルを貼りつける場面があり、手動ではかなりの時間がかかったため、効率化をのためのメモを残しておきます。

前提として、全画像ファイルが同一フォルダに置かれているものとします。また、画像ファイルの入っているフォルダには、画像ファイル以外にはPythonスクリプトファイルのみ置かれているものとします。

#---
#!/usr/bin/env python
# -*- coding: UTF-8 -*-

import os
import win32com.client as win32

def insertImagesIntoWord(arg):

    wordApp = win32.gencache.EnsureDispatch('Word.Application') #create a word application object
    wordApp.Visible = 1 # Wordを表示します
    doc = wordApp.Documents.Add() # create a new application

    doc.PageSetup.RightMargin = 15 # Wordのページの右側余白を指定します
    doc.PageSetup.LeftMargin = 15 # Wordのページの左側余白を指定します
    doc.PageSetup.Orientation = win32.constants.wdOrientLandscape
    # A4 サイズ: 595x842
    doc.PageSetup.PageWidth = 595
    doc.PageSetup.PageHeight = 842

    total_column = 3 # Wordの表の列数を指定します
    total_row = 17 # Wordの表の行数を指定します
    rng = doc.Range(0,0)
    rng.ParagraphFormat.Alignment = win32.constants.wdAlignParagraphCenter
    table = doc.Tables.Add(rng,total_row, total_column)
    table.Borders.Enable = False
    if total_column > 1:
   table.Columns.DistributeWidth()

    frame_max_width= 167 # the maximum width of a picture
    frame_max_height= 125 # the maximum height of a picture

    for index, filename in enumerate(filenames):

        if filename[len(filename)-4: len(filename)].upper() == 'JPEG':

# 各画像を貼りつける位置を計算します
cell_column= index % total_column + 1
cell_row = index / total_column + 1

# セルの形式を整えます
cell_range= table.Cell(cell_row, cell_column).Range
cell_range.ParagraphFormat.LineSpacingRule = win32.constants.wdLineSpaceSingle
cell_range.ParagraphFormat.SpaceBefore = 0
cell_range.ParagraphFormat.SpaceAfter = 3

# ここで画像を貼りつけています
current_pic = cell_range.InlineShapes.AddPicture(os.path.join(os.path.abspath("."), filename))
width, height = (frame_max_height*frame_max_width/frame_max_height, frame_max_height)

# 画像の大きさを表のセルサイズに合わせる場合はこちらも追加します
#current_pic.Height= height
#current_pic.Width= width

# 各セルに対応する画像のファイル名を入力します
table.Cell(cell_row, cell_column).Range.InsertAfter("\n"+filename)


if __name__ == "__main__":

    currentDir = os.getcwd() # スクリプト実行時のカレントディレクトリのパスを取得します
    filenames = os.listdir(currentDir)
    insertImagesIntoWord(filenames)
#---

こちらがベースです。
ファイルがJPG形式かどうかを確認する部分の書き方がくどく感じますが、これで当初の目的はほぼ果たせました。


2016/07/15追記
対象のフォルダ内に画像ファイルとスクリプトファイル以外のファイルが存在すると、画像の貼り付けが表の左上からではなく、ずれてしまいます。

SyntaxHighlighter