长线小白龙 发表于 2021-4-12 19:28 
这个比较难啊,需要用Python操作系统里的进程。。。
from win32com.client import Dispatch
def close_excel_file(file = 'output.xlsx'):
xlApp = Dispatch('Excel.Application')
xlApp.DisplayAlerts = False # 设置不显示警告和消息框
#xlBook = xlApp.Workbooks.Open(file)
workbooks_n = xlApp.Workbooks.Count
print(f'已打开工作簿的数量为:{workbooks_n}个')
if workbooks_n < 0:return
for i in range(1, workbooks_n + 1):# 工作簿索引从1开始
path_ = xlApp.Workbooks(i).Path
name_ = xlApp.Workbooks(i).Name
path = path_+ "\\backup_" + name_
# print(f'第{i}个excel的文件路径为:{path}')
if(file in path):
xlApp.Workbooks(i).Close() #关闭当前打开的文件,不保存文件
# xlApp.Workbooks(i).Activate()
# xlApp.Workbooks(i).SaveAs(path)
# xlApp.Workbooks(path).Close()
# xlApp.Quit() #关闭所有打开的excel文件
del xlApp
这种方法可以解决掉已手动打开的excel