- 下载Python3.0以上版本
- CMD 中输入以下插件下载,代码中会使用到
- pip install pandas
- pip install openpyxl
- 功能:
- Python 读取指定Excel文件中各sheet名,去搜索当前文件夹中的.xlsx文件;
- 当sheet名与.xlsx文件名相同时,将.xlsx文件中的A1:F30区域内容复制到sheet的A1:F30区域;
- sheet名未搜索到,可跳过继续搜寻其它文件;
- 保存;
- 代码内容:
-
import os import pandas as pd import openpyxl # 定义搜索目录和目标文件 search_dir = os.getcwd() # 当前目录 target_file = '1.xlsx' # 加载目标工作簿 wb_target = openpyxl.load_workbook(target_file) # 遍历目录中所有文件 for file_name in os.listdir(search_dir): if file_name.endswith('.xlsx'): # 确保是Excel文件 file_path = os.path.join(search_dir, file_name) # 加载Excel文件 df_source = pd.read_excel(file_path) for sheet_name in df_source.sheetname: # 遍历文件的每个sheet try: # 获取目标工作簿的对应sheet ws_target = wb_target[sheet_name] # 将源文件中的指定区域内容复制到目标工作簿的对应sheet的指定区域 for i in range(1, 31): # A1:F30,共30行,每行6个单元格(A1:F1) for j in range(6): # 每行的6个单元格 ws_target.cell(row=i, column=j+1, value=df_source.iloc[i-1, j]) # 数据写入的位置需要根据实际需求进行调整 except KeyError: # 如果未搜索到对应sheet,跳过并继续搜索其它Sheet pass # 保存目标工作簿 wb_target.save(target_file)
-
- 结果:
- 暂无,符合目标思路。