import os
import pandas as pd
from openpyxl import load_workbook
import threading
def process_excel_files_in_folder(folder_path):
for filename in os.listdir(folder_path):
if filename.endswith(‘.xlsx’): # 仅考虑 Excel 文件
excel_file_path = os.path.join(folder_path, filename)
process_single_excel(excel_file_path)
def process_single_excel(excel_file_path):
# 读取包含所有工作表的 Excel 文件
excel_data = pd.read_excel(excel_file_path, sheet_name=None)
# 处理每个工作表
for sheet_name, df in excel_data.items():
# # 读取第2行的数据
# second_row_data = df.iloc[1]
# # 更新第1行数据格式与第2行保持一致
# for col_name, cell_value in second_row_data.items():
# df[col_name] = df[col_name].astype(type(cell_value))
## 3. 复制列的值
df['PpHSOMEIP_HVPInfo_T_Element.S_Alive'] = df[
'PpFusionHeartBeat_FusionHeartBeat.FusionHeartBeat_signal']
# # 4. 复制列的值
df['PpIdtCanSignal_ESC_FD_7_ESC_FD_7.ESC_Activehold'] = df[
'PpVehCtrlProc_HandShakeResult_T_Element.VehCtrlProc_ACTHandShakeOK']
# 读取第2行的数据
second_row_data = df.iloc[1]
# 更新第1行数据格式与第2行保持一致
for col_name, cell_value in second_row_data.items():
df[col_name] = df[col_name].astype(type(cell_value))
with pd.ExcelWriter(excel_file_path, engine='openpyxl') as writer:
writer.book = load_workbook(excel_file_path)
writer.sheets = dict((ws.title, ws) for ws in writer.book.worksheets)
if sheet_name in writer.sheets:
# 如果工作表存在,将数据框写入该工作表
df.to_excel(writer, index=False, sheet_name=sheet_name)
else:
# 如果工作表不存在,创建一个新工作表并将数据框写入
df.to_excel(writer, index=False, sheet_name=sheet_name)
def process_excel_files_in_folder_multithread(folder_path):
# 获取当前文件夹下的所有 Excel 文件
excel_files = [file for file in os.listdir(folder_path) if file.endswith(‘.xlsx’)]
# 创建线程列表
threads = []
# 多线程处理每个 Excel 文件
for file in excel_files:
thread = threading.Thread(target=process_single_excel, args=(os.path.join(folder_path, file),))
threads.append(thread)
thread.start()
# 等待所有线程完成
for thread in threads:
thread.join()
if name == “main”:
folder_path = r’D:\Test\AMP\modify’
# 1. 读取excel第2行的数据,使excel的第1行数据格式与第2行的数据格式保持一致
process_excel_files_in_folder(folder_path)
# 2. excel多线程运行上面脚本
process_excel_files_in_folder_multithread(folder_path)
学习链接参考:
https://www.oschina.net/search?identification=1703831683711&scope=all&q=os.path.join