win32com python 异常行为

win32com python unusual behaviour

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'

哈哈哈......我以前用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)