LoginSignup
10
16

More than 1 year has passed since last update.

フォルダ内の画像をまとめてエクセルに貼り付け

Last updated at Posted at 2021-07-11

Pythonで作成した画像やネットで拾ってきた画像を1つのエクセルファイルに張り付けて保存する。
画像はA列に貼り付けます。各画像は重ならないようにはしているつもりです。

import tkinter as tk 
import tkinter.filedialog as fl 
import tkinter.messagebox as mb 
import openpyxl as px
import math

PIX_PER_CELL_HEIGH = 18 #エクセルの1セルの高さ当たりのピクセル数

root = tk.Tk()

#ファイルダイアログを表示するディレクトリ
INI_DIR = "D:/Python/Hello"

#GUIのボタンを押した時の処理
def get(*args):
    #CSVファイルを選択する ※複数選択可
    filetype = [('png file', '*.png'), ("jpg file",".jpg"), ('jpeg file', '*.jpeg')]
    path_list = fl.askopenfilenames(initialdir=INI_DIR,
                                    filetypes=filetype,
                                    title="select file")

    #保存用Excelファイル名を指定する
    typ = [("Excel", ".xlsx")]
    savefile = fl.asksaveasfilename(title="保存ファイル名を指定",
                                    filetypes=typ,
                                    initialdir=INI_DIR)

    #書き込み&グラフ描画用のExcelを新規作成
    wb = px.Workbook()

    #Excel内に新しいシートを作成してファイル名をつける
    wb.create_sheet(index=0, title='グラフ')
    ws = wb['グラフ']
    #自動で作成される不要なシートであるSheetを削除
    wb.remove(wb['Sheet'])

    #画像を貼り付けるセル位置の初期化(1行目)
    paste_cell = 1

    # 読み取った複数のCSVファイルを1つのExcelファイルにまとめる
    for i, path in enumerate(path_list):
        # グラフの画像読み出し
        img = px.drawing.image.Image(path)

        # 画像を貼り付ける位置をExcel形式で表す(列のアルファベット+行の番号)
        inColLetter = px.utils.get_column_letter(1) #エクセルの1列目(A列)を指定
        inCellLetter = inColLetter + str(paste_cell) #各ファイルの画像を重ならないように貼り付ける

        #シートにグラフを追加
        ws.add_image(img, inCellLetter)

        # グラフの画像の高さ[pixel]情報から次に貼り付ける画像のセル位置を算出
        paste_cell += math.ceil(img.height / PIX_PER_CELL_HEIGH)


    #Excelデータを保存
    wb.save(savefile + ".xlsx")

    #処理が完了したことをユーザーに知らせる
    mb.showinfo("確認","Excelファイルの作成が完了しました")
    message["text"] = "処理が完了しました"

message = tk.Label(root, text="ファイルを選択してください", width=30)
message.grid(row=0, column=0)

button = tk.Button(text="開く", command=get)
button.grid(row=0, column=1)

root.mainloop()
10
16
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
10
16