python 批量处理excel,把A列的值,赋值给B列

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

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值