从excel单元格读取数字并并按顺序在指定文件夹内查找并合并包含数字的文件,最后输出为一个文件。
一、读取excel单元格内容,这步没问题
二、并在PPT文件夹内获取对应的文件 这步实现不了,用魔法指令也尝试了很多次也不行,可能是我没优化好麻烦帮我修改下谢谢
三、合并成一个新的文件。目前合并成一个文件是空的
# 使用此指令前,请确保安装必要的Python库,例如使用以下命令安装:
# pip install pandas
# pip install openpyxl
import os
import pandas as pd
from typing import *
from xbot import print
def find_and_merge_files_from_excel_cells(excel_path, sheet_name, cells, folder_path, output_file):
"""
title: 从Excel单元格读取数字并按顺序在指定文件夹内查找并合并包含该数字的文件(保留原格式)
description: 读取Excel文件中特定单元格的数字,并按顺序在指定的文件夹内查找文件名包含该数字的文件,并将找到的文件内容保留原格式合并到一个输出文件中。
inputs:
- excel_path (file): Excel文件路径,eg: "data.xlsx"
- sheet_name (str): Excel工作表名称,eg: "Sheet1"
- cells (list): 单元格位置列表,eg: ["A1", "B2", "C3"]
- folder_path (folder): 要查找文件的文件夹路径,eg: "C:/files"
- output_file (file): 合并后的输出文件路径,eg: "merged_output.txt"
outputs:
- None
"""
# 读取Excel文件中特定单元格的内容
df = pd.read_excel(excel_path, sheet_name=sheet_name, header=None, index_col=None)
numbers_to_find = [str(df.at[int(cell[1:])-1, ord(cell[0].upper())-65]) for cell in cells]
found_files = []
# 遍历文件夹,按顺序查找文件名包含特定数字的文件
for number in numbers_to_find:
for root, dirs, files in os.walk(folder_path):
for file in files:
if number in file:
file_path = os.path.join(root, file)
found_files.append(file_path)
break # 找到一个文件后跳出当前循环,继续查找下一个数字
# 合并找到的文件内容,保留原格式
with open(output_file, 'wb') as outfile:
for file_path in found_files:
with open(file_path, 'rb') as infile:
outfile.write(infile.read())
outfile.write(b"\n") # 添加换行符以分隔文件内容
print(f"All found files have been merged into {output_file}")