Python and Excel: Overwriting an existing file always prompts, despite XlSaveConflictResolution value

只谈情不闲聊 提交于 2019-12-18 08:20:46

问题


I'm using the Excel.Application COM object from a Python program to open a CSV file and save it as an Excel workbook. If the target file already exists, then I am prompted with this message: "A file named '...' already exists in this location. Do you want to replace it?" That message comes up despite the fact that I have set the XlSaveConflictResolution value to xlLocalSessionChanges, which is supposed to automatically overwrite the changes without prompting -- or so I thought.

I'm using Microsoft Office Excel 2007 (12.0.6535.5002) SP2 MSO and ActivePython 2.6.5.14. I have tried all three of the XlSaveConflictResolution values using both constants and integers. I have not tried different versions of Excel.

Here's a code snippet:

import win32com.client
xl = win32com.client.gencache.EnsureDispatch("Excel.Application")
wb = xl.Workbooks.Open(r"C:\somefile.csv")
wb.SaveAs(r"C:\somefile.xls", win32com.client.constants.xlWorkbookNormal, \
    None, None, False, False, win32com.client.constants.xlNoChange, \
    win32com.client.constants.xlLocalSessionChanges)

And here's the spec from Microsoft about the SaveAs method for an Excel workbook object: http://msdn.microsoft.com/en-us/library/microsoft.office.tools.excel.workbook.saveas(VS.80).aspx

Could this be a new "feature" in Excel 2007, or did I just do something wrong?


回答1:


Before saving the file set DisplayAlerts to False to suppress the warning dialog:

xl.DisplayAlerts = False

After the file is saved it is usually a good idea to set DisplayAlerts back to True:

 xl.DisplayAlerts = True


来源:https://stackoverflow.com/questions/3373955/python-and-excel-overwriting-an-existing-file-always-prompts-despite-xlsavecon

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!