需求 : 一個 Excel 有多個列, 需要提取部分的列. 生成一個新的 Excel
python 依賴 tkinter, pandas
# -*- coding: UTF-8 -*-
import tkinter as tk
from tkinter import filedialog, RIGHT, Scrollbar, Y, LEFT
from os import walk
import pandas as pd
import random
class Application(tk.Frame):
# 記錄 excel 表頭
excel_columns = []
# 記錄對應的 excel 列的狀態
excel_columns_checkbutton_state = []
directory_path = ''
def __init__(self, master=None):
super().__init__(master)
self.export_button = tk.Button(self)
self.quit = tk.Button(self, text="退出", fg="red", command=self.master.destroy)
self.file_dialog = tk.Button(self)
self.master = master
self.pack()
self.create_widgets()
def create_widgets(self):
# 選擇日誌文件的按鈕
self.file_dialog["text"] = "選擇日誌文件"
self.file_dialog["command"] = self.create_file_dialog
self.file_dialog.pack(side="left")
# 導出 Excel 的列
self.export_button["text"] = "導出選中列"
self.export_button["command"] = self.export_excel_column
self.export_button.pack(side=LEFT)
# 退出按鈕
self.quit.pack(side="left")
def export_excel_column(self):
print(list(map((lambda var: var.get()), self.excel_columns_checkbutton_state)))
result_data = pd.DataFrame() # 建立一個空的dataframe
target_export_columns = []
for i in range(len(self.excel_columns_checkbutton_state)):
if self.excel_columns_checkbutton_state[i].get() == 1:
target_export_columns.append(self.excel_columns[i])
for path, dirs, files in walk(self.directory_path, topdown=False): # 這裏我們的數據都存儲在文件夾下
print(files)
print("要導出的列是: ", target_export_columns)
print(self.excel_columns)
for i in range(len(files)):
# 讀取每個 excel 文件中的數據
target_data = pd.read_excel(self.directory_path + '/%s' % files[i], usecols=target_export_columns)
print("target_data 的類型是: ", type(target_data))
col_mean = target_data[target_export_columns].mean()
# 將每個excel中的數據存儲到之前建好的空的 data frame 中
result_data = result_data.append(col_mean, ignore_index=True)
writer = pd.ExcelWriter(self.directory_path + '/output.xlsx')
result_data.to_excel(writer, 'AllData') # 這裏“AllData”是sheet的名字
writer.save() # 執行完這一步之後,合併後的表格就保存
def create_file_dialog(self):
file_path = filedialog.askdirectory()
self.directory_path = file_path
for directory_path, dirs, files in walk(file_path, topdown=False): # 這裏我們的數據都存儲在文件夾下
print(files)
print("files 類型是:", type(files))
# 得到 Excel 表頭
first_data_frame = pd.read_excel(file_path + '/%s' % files[0])
print(first_data_frame.columns.values)
print(type(first_data_frame.columns.values))
# 生成 Excel 表頭的 checkbutton
excel_columns_count = -1
rows_count = 0
columns_count = 0
print(len(first_data_frame.columns.values))
for col in first_data_frame.columns.values:
excel_columns_count = excel_columns_count + 1
print(col)
# 記錄 Excel 表頭的列名
self.excel_columns.append(col)
y = tk.IntVar()
self.excel_columns_checkbutton_state.append(y)
ct = [random.randrange(256) for x in range(3)]
brightness = int(round(0.299 * ct[0] + 0.587 * ct[1] + 0.114 * ct[2]))
ct_hex = "%02x%02x%02x" % tuple(ct)
bg_colour = '#' + "".join(ct_hex)
b = tk.Checkbutton(self.master, text=col, fg='White' if brightness < 120 else 'Black', bg=bg_colour, variable=y)
if excel_columns_count % 15 == 0:
columns_count = columns_count + 1
rows_count = 0
rows_count = rows_count + 1
b.place(x=250 * columns_count, y=rows_count * 70)
if __name__ == '__main__':
root = tk.Tk()
# scrollbar = Scrollbar(root)
# scrollbar.pack(side=RIGHT, fill=Y)
root.geometry("1500x900+200+50")
app = Application(master=root)
app.mainloop()