close excel by keyword 根据关键字关闭 excel 窗口 xlwings 方式实现
根据标题关键字关闭 workbook,如果没有打开的 workbook 则退出 excel
xlwings 方式实现 更方便快捷
def close_excel_by_keyword(keyword):
if '~$' in keyword:
return
app = xw.apps.active
for workbook in app.books:
if keyword in workbook.name:
workbook.close()
file_list = os.listdir(mb51_dir)
print('file list', file_list)
while any('~$' in x for x in file_list):
file_list = os.listdir(mb51_dir)
for file in file_list:
close_excel_by_keyword(file)
time.sleep(1)
import win32com.client
import win32gui
def close_excel_by_keyword(keyword):
# 获取当前所有窗口的句柄
hwnds = []
win32gui.EnumWindows(lambda hwnd, param: param.append(hwnd), hwnds)
# 遍历窗口句柄,查找包含关键字的 Excel 窗口并关闭
for hwnd in hwnds:
text = win32gui.GetWindowText(hwnd)
if keyword in text:
excel = win32com.client.Dispatch("Excel.Application")
try:
workbooks = excel.Workbooks
for workbook in workbooks:
if keyword in workbook.Name:
workbook.Close(False)
except Exception as e:
pass
try:
excel = win32com.client.GetActiveObject("Excel.Application")
workbooks = excel.Workbooks
print(workbooks.Count)
if workbooks.Count == 0:
# 如果没有打开的工作簿,关闭 Excel.Application
excel.Quit()
except:
# 如果没有 Excel.Application 实例,不需要关闭
pass
def main():
keyword = "tw" # 替换为你要查找的关键字
close_excel_by_keyword(keyword)
if __name__ == "__main__":
main()