【Windows10/openpyxl】ExcelファイルをGUIベースで選択して読み込む方法。

Python

環境
Windows10
Python3.7.7
openpyxl3.0.3
tkinter8.6

openpyxlはpythonでExcelファイルを操作することができるライブラリです。
以下のような形でファイルを読み込むことができます。

import openpyxl
workbook = openpyxl.load_workbook('Book1.xlsx')

ここでは静的にBook1.xlsxを読み込んでいますが、GUIベースでファイルを選択してロードしたいというニーズは多いと思います。

ここではpythonでGUIを構築できるtkinterを使用して、動的にExcelファイルを読み込みます。

完成イメージは以下です。


コードは以下です。

import os,sys
import openpyxl
from tkinter import Tk,StringVar,ttk,filedialog,messagebox,LEFT

#参照ボタンクリック時
def ref_clicked():
    fTyp = [("EXCELファイル","*.xlsx")]
    iDir = os.path.abspath(os.path.dirname(__file__))
    filepath = filedialog.askopenfilename(filetypes = fTyp,initialdir = iDir)
    file1.set(filepath)

# スタートボタンクリック時
def start_clicked(fp):
    if fp:
        workbook = openpyxl.load_workbook(fp)
        messagebox.showinfo("結果", file1.get())

if __name__ == '__main__':
    #ウインドウの設定
    root = Tk()
    root.title('EXCELファイルを選択して下さい')
    root.resizable(False, False)

    #Frame1の作成
    frame1 = ttk.Frame(root, padding=10)
    frame1.grid()

    # 参照ボタンの作成
    button1 = ttk.Button(root, text=u'参照', command=ref_clicked)
    button1.grid(row=0, column=3)

    #ファイルラベルの作成
    s = StringVar()
    s.set('ファイル>>')
    label1 = ttk.Label(frame1, textvariable=s)
    label1.grid(row=0, column=0)

    # 参照パスラベルの作成
    file1 = StringVar()
    file1_entry = ttk.Entry(frame1, textvariable=file1, width=50)
    file1_entry.grid(row=0, column=2)

    #frame2の作成
    frame2 = ttk.Frame(root, padding=(0,5))
    frame2.grid(row=1)

    # Startボタンの作成
    stButton = ttk.Button(frame2, text='Start', command=lambda: start_clicked(file1.get()))
    stButton.pack(side=LEFT)

    # Cancelボタンの作成
    button3 = ttk.Button(frame2, text='Cancel', command=lambda: sys.exit())
    button3.pack(side=LEFT)

    root.mainloop()
タイトルとURLをコピーしました