选择文件夹后,将文件夹内多个excel中,删除全部不符合配置文件中设定的sheet名称的工作表
时间: 2023-05-16 13:05:08 浏览: 77
您可以使用Python中的pandas库来完成这个任务。首先,您需要读取配置文件和文件夹中的所有Excel文件。然后,您可以使用pandas的read_excel函数来读取每个Excel文件中的所有工作表。接下来,您可以使用pandas的drop函数来删除不符合配置文件中设定的sheet名称的工作表。最后,您可以使用pandas的to_excel函数将修改后的Excel文件保存回原始文件夹中。
以下是示例代码:
```python
import os
import pandas as pd
# 读取配置文件
config_file = 'config.txt'
with open(config_file, 'r') as f:
sheet_names = f.read().splitlines()
# 遍历文件夹中的所有Excel文件
folder_path = 'path/to/folder'
for filename in os.listdir(folder_path):
if filename.endswith('.xlsx'):
file_path = os.path.join(folder_path, filename)
# 读取Excel文件中的所有工作表
sheets_dict = pd.read_excel(file_path, sheet_name=None)
# 删除不符合配置文件中设定的sheet名称的工作表
for sheet_name in sheets_dict.keys():
if sheet_name not in sheet_names:
sheets_dict.pop(sheet_name)
# 将修改后的Excel文件保存回原始文件夹中
with pd.ExcelWriter(file_path) as writer:
for sheet_name, sheet_data in sheets_dict.items():
sheet_data.to_excel(writer, sheet_name=sheet_name, index=False)
```
请注意,此代码仅供参考,您需要根据您的具体需求进行修改。