win32com.client:如何使用DispatchEx复制工作表?

时间:2018-05-01 15:47:56

标签: python excel windows win32com

如何使用DispatchEx复制工作表?我无法从一个工作表从一个工作簿复制到另一个工作簿上的另一个工作表。我正在使用DispatchEx在两个单独的Excel中打开它们。行:ws1.Copy(Before=wb2.Worksheets(1))发出错误。同一行适用于调度,但我需要在excel中单独打开文件。

import time, os.path, os
from win32com.client import DispatchEx

path1 = 'C:\\example1.xlsx'
path2 = 'C:\\example2.xlsx'

xla = DispatchEx("Excel.Application")
xla.DisplayAlerts = False
xla.Visible = True

xl = DispatchEx("Excel.Application")
xl.DisplayAlerts = False
xl.Visible = True

curTime = os.path.getmtime('C:\\example1.xlsx')

while True:

    modTime = os.path.getmtime('C:\\example1.xlsx')

    if(modTime > curTime):

        wb1= xla.Workbooks.Open(Filename=path1)
        wb2= xl.Workbooks.Open(Filename=path2)
        ws1 = wb1.Worksheets(1)
        ws2 = xl.ActiveSheet
        ws1.Copy(Before=wb2.Worksheets(1))  # problem code here. Works in
                                            # dispatch 

这是'ws1.Copy(Before = wb2.Worksheets(1))'语句下面的内容。唯一的区别是我使用Dispatch在一次实例中打开两个工作簿。这样做可以让我将ws1复制到wb2。但是主文件已关闭,即使我指定wb1.close(),也会抛出msg'文件进行编辑'。

        wb1.Close()                         #close wb1 but still get msg
        #xla.Quit()                         #Quit() is the only way I can 
                                            #close out wb1 completely and 
                                            #not receive the  'file now 
                                            #available for edit' msg.  
                                            #But it close both books. 

        xla = Dispatch("Excel.Application") #starts up wb1 again if file 
                                            #is modified (path 1)
        xla.DisplayAlerts = False
        xla.Visible = True

这是我得到的追溯:忽略第35行,因为这里没有插入一些注释行。

Traceback (most recent call last):
  File "C:/Python34/updateExcel2Dispatch.py", line 35, in <module>
  ws1.Copy(Before=wb2.Worksheets(1))
  File "<COMObject <unknown>>", line 3, in Copy
  pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, 'Microsoft Office Excel', 'Copy method of Worksheet class failed', 'C:\\Program
  Files (x86)\\Microsoft Office\\Office12\\1033\\XLMAIN11.CHM', 0, -2146827284), None)"

0 个答案:

没有答案