根据标题关键字关闭 workbook,如果没有打开的 workbook 则退出 excel
xlwings 方式实现 更方便快捷
def close_excel_by_keyword(keyword):if '~$' in keyword:returnapp = xw.apps.activefor 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 win32guidef 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.Workbooksfor workbook in workbooks:if keyword in workbook.Name:workbook.Close(False)except Exception as e:passtry:excel = win32com.client.GetActiveObject("Excel.Application")workbooks = excel.Workbooksprint(workbooks.Count)if workbooks.Count == 0:# 如果没有打开的工作簿,关闭 Excel.Applicationexcel.Quit()except:# 如果没有 Excel.Application 实例,不需要关闭passdef main():keyword = "tw" # 替换为你要查找的关键字close_excel_by_keyword(keyword)if __name__ == "__main__":main()