我是只會excel新手,VBA、巨集也都不太會的那種,最近要來處理龐大數量且稱差不齊的excel檔案,真是一大難題,本身也沒有任何程式語言經驗,我決定用chatGPT自學excel python相關語法,以下是筆記內容
網路論壇上有許多安裝python、執行的教學,就不多做贅述
若是有問題歡迎留言討論
tkinter
)import tkinter as tk
from tkinter import filedialog, messagebox
root = tk.Tk()
root.withdraw() # 隱藏主視窗
folder = filedialog.askdirectory(title="選擇資料夾") # 選擇資料夾
messagebox.showinfo("通知", f"選擇的資料夾: {folder}") # 顯示選擇結果
pandas
)import pandas as pd
xls = pd.ExcelFile("data.xlsx") # 讀取 Excel 檔案
df = pd.read_excel(xls, sheet_name="頭頸CTCAE", engine="openpyxl") # 讀取特定工作表
df_transposed = df.T # 轉置 DataFrame
df_transposed.to_excel("new_file.xlsx", index=False, header=False, engine="openpyxl")
os
)import os
files = os.listdir("資料夾路徑") # 取得資料夾內所有檔案名稱
if file.endswith(".xlsx") and not file.startswith("~$"): # 避免處理 Excel 暫存檔
file_name = os.path.splitext("data.xlsx")[0] # 取得 "data"(去掉 .xlsx)
new_filename = f"{file_name}_頭頸CTCAE.xlsx"
import hashlib
def calculate_file_hash(df):
hash_md5 = hashlib.md5()
hash_md5.update(pd.util.hash_pandas_object(df, index=True).values.tobytes())
return hash_md5.hexdigest()
def needs_update(new_file_path, transposed_df):
if not os.path.exists(new_file_path):
return True # 目標檔案不存在,直接儲存
try:
existing_df = pd.read_excel(new_file_path, engine='openpyxl')
return calculate_file_hash(transposed_df) != calculate_file_hash(existing_df) # 內容不同才更新
except Exception:
return True # 讀取失敗時,強制更新
log_messages = ["更新檔案: example.xlsx", "跳過未變更檔案: sample.xlsx"]
with open("Transpose_Log.txt", "w", encoding="utf-8") as log_file:
log_file.write("\n".join(log_messages))