ラベル win32com の投稿を表示しています。 すべての投稿を表示
ラベル win32com の投稿を表示しています。 すべての投稿を表示

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

2015年11月6日金曜日

Windowsダイアログを使って編集するファイルを指定する方法1 | Python

Excelファイルでのデータ処理をPythonで記述したスクリプトを使って行う場合を想定します。

---
import win32com.client

xlApp = win32com.client.Dispatch("Excel.Application")
xlApp.Visible = 1

xlApp.Workbooks.open(r"C:\training\test.xlsx")
xlSheet = xlApp.Workbooks(1).Sheets(1)

xlCell = xlSheet.Cells(2,1)
xlCell.Value = "aaa"
---

これを実行すると新規にExcelが起動し、セルA2にaaaが入力されます。

次に、Windowsのダイアログから開きたいファイルを指定する方法です。

---
import win32com.client
import win32ui #ダイアログを開くために追記します

o = win32ui.CreateFileDialog( 1, ".txt", "default.txt", 0, "Text Files (*.txt)|*.txt|All Files (*.*)|*.*|")
o.DoModal() #( )内はダイアログ上の表示を規定しています

xlApp = win32com.client.Dispatch("Excel.Application")
xlApp.Visible = 1

xlFile = o.GetPathName() #ダイアログで指定したファイルのパスを変数xlFileに入れています

xlApp.Workbooks.open(xlFile)
xlSheet = xlApp.Workbooks(1).Sheets(1)

# A2セルにaaaと書き込む
xlCell = xlSheet.Cells(2,1)
xlCell.Value = "aaa"
---

これでダイアログから開きたいファイルを指定することができます。

ファイル名は隠しています


しかし、問題もあります。
それは、ダイアログでキャンセルボタンが押された時の処理が書かれていないことです。
これについての対応方法は別の投稿で書きたいと思います。

2014年9月2日火曜日

Python | Excelファイルの読み込み方法

Pythonを使ってExcelファイルを操作する方法です。

まずはファイルを読み込んで、指定のセルの値を表示してみます。

---以下スクリプト---

import win32com.client #

xlApp = win32com.client.Dispatch("Excel.Application")

xlApp.Visible = 1

xlApp.Workbooks.open(r"C:\test.xlsx")
xlSheet = xlApp.Workbooks(1).Sheets(1)
xlCell = xlSheet.Cells(7, 3)
value = xlCell.value

xlApp.Quit()

print "Cell(7,3)->", value

---以上スクリプト---

まず、Excelを使うのにwin32comとExcelがインストールされている必要があります。

Python用Windows extensionダウンロードサイト
http://sourceforge.net/projects/pywin32/

その上でimportして使います。

上の例では読み込んだExcelファイルのワークシート1にあるセルC7の値を取得して表示します。
xlCell = xlSheet.Cells(7, 3)ではセル位置を(row, column)で指定するため、

(7, 3) = C7

となります。

SyntaxHighlighter