[英]Python - Is there a way I can dynamically play with data in Excel file using Openpyxl
What can I do to make this work?我能做些什么来完成这项工作? This program executes successfully but shows this error
该程序执行成功但显示此错误
if (sh2.cell(r+1,c).value) > 500: TypeError: '>' not supported between instances of 'NoneType' and 'int' All it does is, selects Price that are greater than $500 and color codes the cells in the Excel. if (sh2.cell(r+1,c).value) > 500: TypeError: '>' not supported between 'NoneType' and '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:
- will throw an exception if sh2.cell(r+1,c).value
is None
(which is Pythons equivalent of null). if (sh2.cell(r+1,c).value) > 500:
- 如果sh2.cell(r+1,c).value
为None
(这相当于 Python 的 null),将抛出异常。
The value will most likely contains None
because you're looping throw a rage of sh2.max_row+2
( you probably don't need the + 2 )该值很可能包含
None
因为您正在循环抛出sh2.max_row+2
的愤怒(您可能不需要 + 2 )
One solution to get around this issue is to always check value is not null by using if sh2.cell(r+1,c).value and...
.解决此问题的一种解决方案是使用
if sh2.cell(r+1,c).value and...
始终检查 value is not null。 For example if sh2.cell(r+1,c).value and (sh2.cell(r+1,c).value) > 500:
例如
if sh2.cell(r+1,c).value and (sh2.cell(r+1,c).value) > 500:
Alternatively you can set a default of 0 using or
operator.或者,您可以使用
or
运算符设置默认值 0。 Eg: if (sh2.cell(r+1,c).value or 0) > 500:
例如:
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")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.