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'

最佳答案

HAHAHA.....,我以前在使用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)

关于python - win32com python异常行为,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/60430951/

10-12 18:54