如何使用win32com.client将xls重新保存到xlsx时禁用/ autoanswer关于macros/ VB项目的对话框?

当使用这个代码时:

import win32com.client as win32 input_files = os.listdir(parent_dir) input_files = [parent_dir + i for i in input_files if i.endswith('.xls') and not i.endswith('.xlsx')] for input_file in input_files: if not os.path.isfile(input_file.replace('.xls', '.xlsx')): excel = win32.gencache.EnsureDispatch('Excel.Application') wb = excel.Workbooks.Open(input_file) wb.SaveAs(input_file + "x", FileFormat=51) # FileFormat = 51 is for .xlsx extension wb.Close() # FileFormat = 56 is for .xls extension excel.Application.Quit() 

在包含一些macros/ VB项目的Excel文件中,经常有messagebox显示出来的警告,所有的macros/ VB项目将会丢失,我想以某种方式自动地回答它,例如“Yes”,或者可能有一些SaveAs参数function或设置

win32.gencache.EnsureDispatch( 'Excel.Application')?

现在我可以将文件重新保存为带有FileFormat = 51的xlsm,但出于某些安全原因,我不想这样做,我真的不需要在我的文件中使用这个macros/ VB项目。

试过excel.DisplayAlerts =假 – 没有帮助。

也想到像pywinauto的东西,但也许它矫枉过正,也许有更优雅的解决scheme?

运用

 wb.Close(True) #if you need to save .xls file also 

或使用

 wb.Close(False) # if you not decide to save .xls file 

另一方面,它可能有其他文件打开,所以当你使用excel.Application.Quit()并且这些文件不保存时,excel将在closures之前显示确认对话框。