Win32com Python的异常行为

3

我是一个新的win32com用户。下面是我将xlsx文件转换为网页并捕获单元格范围为.png的代码。我遇到的问题是有时候代码运行得很好,但有时会出现错误。

import os
import sys
import win32com.client
from win32com.client.gencache import EnsureDispatch
from win32com.client import constants
from win32com.client import DispatchEx

import PIL
from PIL import ImageGrab


# #---------------------------standalone--------------------------------
path = r'path'
Temp='folder'
#
## ---------------------------------------------------------------------
filename1='Images.html'

images='Images_files'

def A(source):


    xl = EnsureDispatch('Excel.Application')
    wb = xl.Workbooks.Open(yourExcelFile)
    wb.SaveAs(newFileName, constants.xlHtml)
    xl.Workbooks.Close()
    xl.Quit()
    del xl



Allsheets=[]
def B():

    xlApp = win32com.client.DispatchEx('Excel.Application')
    xlApp.Visible = True
    wb = xlApp.Workbooks.Open(os.path.join(path,Temp,source))

    for sh in wb.Sheets:
        Allsheets.append(sh.Name)

    num=1     
    array=["AC7:AF10", "AC28:AF31","AC49:AF52"]
    for sheet_4 in Allsheets[:4]:
        xlApp.Worksheets(sheet_4).Activate()
        win32c = win32com.client.constants
        ws = xlApp.ActiveSheet

        for i in range(len(array)):
            ws.Range(array[i]).CopyPicture(Format=win32c.xlBitmap) 
            img = ImageGrab.grabclipboard()
            img.save(os.path.join(path,Temp,images,'TextBox0'+ f"{num:02}"+'.png'))
            num=num+1



    n=13 
    arry=["K5:M5","X5:Z5","K26:M26","X26:Z26","K47:M47","X47:Z47"]    
    for sheet_name in Allsheets[5:]:

        xlApp.Worksheets(sheet_name).Activate()
        win32c = win32com.client.constants
        ws = xlApp.ActiveSheet

        for i in range(len(arry)):
            ws.Range(arry[i]).CopyPicture(Format=win32c.xlBitmap) 
            img = ImageGrab.grabclipboard()
            img.save(os.path.join(path,Temp,images,'Avg0'+ f"{n:02}"+'.png'))
            n=n+1


    wb.Close(True)
    xlApp.Quit()

for f in os.listdir(os.path.join(path,Temp)):
    if f.endswith('.xlsx'):
        source=f

yourExcelFile = os.path.join(path,Temp,source)
newFileName = os.path.join(path,Temp,filename1)


A(source)
B()

以上代码大多数情况下都可以正常工作,但是对于之前能够正常工作的相同输入数据,现在会抛出以下错误。我已经尝试删除gen_py并重新运行代码。我已经参考了几乎所有的解决方案,但目前没有任何清晰且有效的解决方法。请有人提供一个解决方案。

    img.save(os.path.join(path,Temp,images,'TextBox0'+ f"{num:02}"+'.png'))

AttributeError: 'NoneType' object has no attribute 'save'


错误意味着 ImageGrab.grabclipboard() 返回了 None,即剪贴板中没有包含图像。 - Maximouse
@MaxiMouse,但是为什么有时它会返回图像,有时却不会呢? - Python Bang
你的测试文件总是一样吗? - tst
@tst 是的,它是一样的。 - Python Bang
@MaxiMouse @tst 下面是针对相同输入数据有时会抛出的另一个错误:com_error: (-2147352567, '发生异常。', (0,'Microsoft Excel','Range 类的 CopyPicture 方法失败','xlmain11.chm',0,-2146827284),None) - Python Bang
1个回答

3

哈哈哈……使用 PIL 模块时,我曾经遇到过同样的问题。

AttributeError: 'NoneType' object has no attribute 'save'

我猜如果你调试一下这段代码,它应该能正常运行,对吗?

处理这个问题有两种方式:

import time

    time.sleep(1) # sleep for a while 
    img.save(os.path.join(path,Temp,images,'TextBox0'+ f"{num:02}"+'.png'))

或者(我推荐这个):
while True:
    try:
        img.save(os.path.join(path,Temp,images,'TextBox0'+ f"{num:02}"+'.png'))
        break
    except AttributeError:
        pass
    except Exception as e:
        print(e.args)

睡眠对我有用。While循环停止了执行,既不继续也不停止执行。 - Python Bang
@PythonBang 你使用过“break”来退出这个循环吗? - jizhihaoSAMA
不要使用for循环,如您所建议的,请改用try中的break。for i in range(len(arry)): ws.Range(arry[i]).CopyPicture(Format=win32c.xlBitmap) img = ImageGrab.grabclipboard() while True: try: img.save(os.path.join(path,Temp,images,'TextBox0'+ f"{num:02}"+'.png')) break except AttributeError: pass except Exception as e: print(e.args) n=n+1 - Python Bang
@PythonBang 你有两个地方使用了img = ImageGrab.grabclipboard()。这两个地方需要使用while循环和break吗? - jizhihaoSAMA
@jizihihaoSAMA 是的,它确实这样做。 - Python Bang

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接