Python和Excel:尽管XlSaveConflictResolution的值,但是覆盖现有文件总是提示 [英] Python and Excel: Overwriting an existing file always prompts, despite XlSaveConflictResolution value
问题描述
我使用来自Python程序的Excel.Application COM对象来打开CSV文件并将其保存为Excel工作簿。如果目标文件已经存在,那么我会提示这条消息:一个名为'...'的文件已经存在于这个位置,你要替换它吗?该消息出现,尽管我已设置 XlSaveConflictResolution 值到xlLocalSessionChanges,它应该自动覆盖更改,而不提示 - 或者所以我想。
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.
我使用Microsoft Office Excel 2007(12.0.6535.5002)SP2 MSO和ActivePython 2.6.5.14。我已经尝试所有三个XlSaveConflictResolution值使用常量和整数。我没有尝试过不同版本的Excel。
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.
这里是一个代码片段:
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)
SaveAs方法用于Excel工作簿对象: http://msdn.microsoft.com/en-us/library/microsoft.office.tools.excel.workbook.saveas(VS.80).aspx
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
这可能是Excel 2007中的一个新的功能,或者我做错了什么?
Could this be a new "feature" in Excel 2007, or did I just do something wrong?
推荐答案
在将文件集 DisplayAlerts
保存到 False
之前,可以禁止警告对话框:
Before saving the file set DisplayAlerts
to False
to suppress the warning dialog:
xl.DisplayAlerts = False
保存文件后,通常最好将 DisplayAlerts
恢复为 True
:
After the file is saved it is usually a good idea to set DisplayAlerts
back to True
:
xl.DisplayAlerts = True
这篇关于Python和Excel:尽管XlSaveConflictResolution的值,但是覆盖现有文件总是提示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!