Skip to main content
 首页 » 编程设计

Python:根据值从 Excel 打印单元格

2024年11月01日10zfyouxi

我想根据它们的值从 Excel 中打印一些单元格。在大多数情况下,它可以正常工作,但最后会出错。这是我到目前为止所拥有的...

现在已经解决了,工作脚本在下面

from win32com.client import Dispatch 
import time, pythoncom 
 
xl = Dispatch('Excel.Application') 
wb = xl.Workbooks.Add(r'X:\HR & IT\IT\LOGS\Dynamics Idle Sessions\Copy of Dynamics Idle Sessions.xlsm') 
ws = wb.Worksheets(1) 
xl.Run('Refresh') 
time.sleep(0.5) 
 
idlerow = 6 
 
while idlerow < 32: 
    idletime = ws.Cells(idlerow,3).value 
    user = ws.Cells(idlerow,4).value 
    if idletime is not None: 
        if idletime > 60 and len(user) > 6: 
            print(user,'\thas been logged on to Dynamics for\t',idletime,'\tminutes.') 
        elif idletime > 60 and len(user) <= 6: 
            print(user,'\t\thas been logged on to Dynamics for\t',idletime,'\tminutes.') 
    idlerow += 1 
 
xl.Quit() 
pythoncom.CoUninitialize() 

我得到的错误:

"Traceback (most recent call last): 
  File "X:/HR & IT/Ryan/Python Scripts/DynamicsUsersMT60.py", line 15, in <module> 
    if idletime > 60 and len(user) > 6: 
TypeError: unorderable types: NoneType() > int()" 

如果我将空闲时间设置为 int,我会收到以下错误:

Traceback (most recent call last): 
  File "X:/HR & IT/Ryan/Python Scripts/DynamicsUsersMT60.py", line 13, in <module> 
    idletime = int(ws.Cells(idlerow,3).value) 
TypeError: int() argument must be a string or a number, not 'NoneType' 

这些错误只会出现在脚本似乎已正确运行并打印出我需要的内容之后。有什么帮助吗?

非常感谢。

请您参考如下方法:

看起来 idletime 的值变成了 None,添加一个额外的检查:

if idletime is not None: 
    if idletime > 60 and len(user) > 6: 
        print(user,'\thas been logged on to Dynamics for\t',idletime,'\tminutes.') 
    elif idletime > 60 and len(user) <= 6: 
        print(user,'\t\thas been logged on to Dynamics for\t',idletime,'\tminutes.')