我正在尝试保存由另一个打开的应用程序生成的excel文件。也就是说,excel应用程序处于前台。这个文件有一些数据,需要保存,即写入磁盘。
换句话说,我需要像File->SaveAs这样的操作。
复制步骤:
-
import win32com.client as win32
app = win32.gencache.EnsureDispatch('Excel.Application')
app.Workbooks(1).SaveAs(r"C:\Users\test\Desktop\test.xlsx")
app.Application.Quit()
错误-
Traceback (most recent call last):
File "c:/Users/test/Downloads/automate_excel.py", line 6, in <module>
ti = disp._oleobj_.GetTypeInfo()
pywintypes.com_error: (-2147418111, 'Call was rejected by callee.', None, None)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "c:/Users/test/Downloads/automate_excel.py", line 6, in <module>
app = win32.gencache.EnsureDispatch('Excel.Application')
File "C:\Users\test\AppData\Local\Programs\Python\Python38\lib\site-packages\win32com\client\gencache.py", line 633, in EnsureDispatch
raise TypeError(
TypeError: This COM object can not automate the makepy process - please run makepy manually for this object
发布于 2022-11-16 18:58:08
这是基于@scotscotmcc的答案对我有用的版本。问题是在我运行程序时处于编辑模式的单元格。确保在当前单元格中单击enter,然后在excel中退出编辑模式。
import win32com.client as win32
import random
xl = win32.Dispatch('Excel.Application')
wb = xl.Workbooks['Book1']
wb.SaveAs(r"C:\Users\...\Desktop\Form"+str(random.randint(0,1000))+".xlsx")
wb.Close()
xl.Quit()
发布于 2022-11-15 23:10:16
您的问题可能有很多来源,所以如果您共享进一步的代码,我会接受的。例如,在运行行excel = win32.gencache.EnsureDispatch('Excel.Application')
的多个实例时(例如,在for循环中),可能会发生第二个错误,还请确保有一个完全激活和许可的版本的excel。
发布于 2022-11-16 16:30:13
这对我来说很管用(在python==3.9.8和pywin32==305上)。你会发现第一行和你的不一样,但我想真的是这样。
在此过程中,我们不断地获得工作簿或设置DisplayAlerts的属性错误。我们发现(从这个问题:Excel.Application.Workbooks attribute error when converting excel to pdf),如果Excel在循环中(例如,编辑一个单元格或弹出打开),那么您将得到一个错误。因此,请确保单击“从单元格中输入”,这样就不会对其进行编辑。
import win32com.client as win32
savepath = 'c:\\my\\file\\path\\test\\'
xl = win32.Dispatch('Excel.Application')
wb = xl.Workbooks['Book1']
wb.DisplayAlerts = False # helpful if saving multiple times to save file, it means you won't get a pop-up for overwrite and will default to save it.
filename = 'new_xl.xlsx'
wb.SaveAs(savepath+filename)
wb.Close()
xl.Quit()
编辑:添加pywin32版本,包括更多提示
https://stackoverflow.com/questions/74350835
复制相似问题