简体   繁体   English

win32com python异常行为

[英]win32com python unusual behaviour

New to win32com. win32com 的新手。 Below is my code for converting xlsx file to webpage and capturing the range of cells as .png.下面是我将 xlsx 文件转换为网页并将单元格范围捕获为 .png 的代码。 The problem I am facing is that some times the code run fine but sometimes it throws errors.我面临的问题是有时代码运行良好,但有时会引发错误。

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()

The above code works fine for most of the times but throws the below error for the same input data it was working before.上面的代码在大多数情况下都可以正常工作,但是对于之前工作的相同输入数据会引发以下错误。 I have tried deleting gen_py and rerunning the code.我尝试删除 gen_py 并重新运行代码。 Have referred almost all the solutions but nothing is clear and working as of now.已经提到了几乎所有的解决方案,但目前没有任何明确和有效的解决方案。 Please someone suggest a solution.请有人提出解决方案。

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

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

HAHAHA.....,I used to meet this same problem when I use PIL module. HAHAHA.....,我以前在使用PIL模块时也遇到过同样的问题。

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

I guess that if you debug this code it could run this code normally,right?我猜如果你调试这段代码,它可以正常运行这段代码,对吧?

There are two way to handle this:有两种处理方法:

import time

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

Or (I recommend this):或者(我推荐这个):

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM