需求:
对一个路径下的多个Excel,查询这些Excel里面,固定名称的sheet表,如果存在,就删除,如果不存在就跳过,最后在原路径下进行保存Excel。
使用openpyxl库
import os
from openpyxl import load_workbook
# 指定要删除的工作表名称
sheets_to_delete = ['ArrangementCheck', 'List of models', 'Workability', 'Assemblability', 'Other considerations', 'person in charge', 'distribution list']
# 指定Excel文件所在的路径
path = 'C:\\Input'
# 遍历路径下的所有Excel文件,并删除指定工作表
for file_name in os.listdir(path):
if file_name.endswith('.xlsx'):
file_path = os.path.join(path, file_name)
try:
wb = load_workbook(file_path)
for sheet_name in sheets_to_delete:
if sheet_name in wb.sheetnames:
sheet = wb[sheet_name]
wb.remove(sheet)
wb.save(file_path)
except:
# 如果无法打开文件,或者指定工作表不存在,则跳过该文件并继续执行下一个文件
print(f'Skipping file {file_name}')
continue