0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

グラフを描画してExcelに貼り付ける

Last updated at Posted at 2021-06-10
import tkinter as tk 
import tkinter.filedialog as fl 
import tkinter.messagebox as mb 
import matplotlib.pyplot as plt
import openpyxl as px
import os
import pandas as pd

root = tk.Tk()

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

# GUIのボタンを押した時の処理
def get(*args):
    #CSVファイルを選択する ※複数選択可
    filetype = [('excel file', '*.xlsx'), ("csv file",".csv"), ('excel file', '*.xls')]
    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'])

    # 読み取った複数のCSVファイルを1つのExcelファイルにまとめる
    for i, path in enumerate(path_list):
        read_data = pd.read_excel(path, skiprows=1)

        #データ数、系列数を変数に格納
        data_num, series_num = read_data.shape

        #ファイル名をシート名に設定
        filename = os.path.basename(path)
        basename = os.path.splitext(filename)[0]

        #x軸とするデータ
        x_values = read_data.iloc[:,0]

        #グラフの作成
        fig = plt.figure()
        ax = fig.add_subplot(1,1,1)
        #カラーマップを定義
        cmap = plt.get_cmap("tab10")
        for j in range(1, series_num):
            #y軸とするデータ
            y_values = read_data.iloc[:,j]
            ax.plot(x_values, y_values, label=basename, color=cmap(j))
  
        #グラフを保存
        image_file_path = os.path.dirname(savefile)+"\\"+basename+".png"
        plt.savefig(image_file_path)

        #グラフのメモリ解放
        plt.clf()
        plt.close()

        # 画像を貼り付ける位置をExcel形式で表す(列のアルファベット+行の番号)
        inColLetter = px.utils.get_column_letter(1) #エクセルの1列目(A列)を指定
        inCellLetter = inColLetter + str(28*(i)+1) #各ファイルのデータのグラフを28行間隔で貼り付ける

        # グラフの画像読み出し
        img = px.drawing.image.Image(image_file_path)

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

    #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()
0
2
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
0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?