Python - 有没有一种方法可以使用 Openpyxl 动态播放 Excel 文件中的数据

Python - Is there a way I can dynamically play with data in Excel file using Openpyxl

我该怎么做才能完成这项工作?该程序执行成功但显示此错误
如果 (sh2.cell(r+1,c).value) > 500: 类型错误:'NoneType' 和 'int' 实例之间不支持“>” 它所做的只是选择大于 500 美元的价格,并对 Excel.

中的单元格进行颜色编码
import openpyxl
from openpyxl.styles import PatternFill

wb1 = openpyxl.load_workbook("C:\Users\Ricky\Desktop\UpdatedStock_ex2.xlsx")
sh2 = wb1.active

for r in range(1,sh2.max_row+2):
    for c in range(1,sh2.max_column+1):
        if (sh2.cell(row=1, column=c).value) == "Price":
             if (sh2.cell(r+1,c).value) > 500:
                print(sh2.cell(r+1,c).value)
                sh2.cell(r+1, c).fill = PatternFill("solid","71FF35")
               

wb1.save("C:\Users\Ricky\Desktop\UpdatedStock_ex2.xlsx")
print("file Saved")

if (sh2.cell(r+1,c).value) > 500: - 如果 sh2.cell(r+1,c).valueNone(相当于 Python 的 null),将抛出异常。

该值很可能包含 None,因为您正在循环抛出 sh2.max_row+2 的愤怒(您可能不需要 + 2 )

解决此问题的一个解决方案是始终使用 if sh2.cell(r+1,c).value and ... 检查值是否为空。例如if sh2.cell(r+1,c).value and (sh2.cell(r+1,c).value) > 500:

或者,您可以使用 or 运算符设置默认值 0。例如:if (sh2.cell(r+1,c).value or 0) > 500:

import openpyxl
from openpyxl.styles import PatternFill

wb1 = openpyxl.load_workbook("C:\Users\Ricky\Desktop\UpdatedStock_ex2.xlsx")
sh2 = wb1.active

for r in range(1,sh2.max_row+2):
    for c in range(1,sh2.max_column+1):
        if (sh2.cell(row=1, column=c).value) == "Price":
             # Commented out line below to check not None and value is greater than 500.
             # if sh2.cell(r+1,c).value and (sh2.cell(r+1,c).value) > 500:
             # Code below will convert None to 0 and prevent exception.
             if (sh2.cell(r+1,c).value or 0) > 500:
                print(sh2.cell(r+1,c).value)
                sh2.cell(r+1, c).fill = PatternFill("solid","71FF35")
               

wb1.save("C:\Users\Ricky\Desktop\UpdatedStock_ex2.xlsx")
print("file Saved")