簡體   English   中英

Python - 有沒有辦法可以使用 Openpyxl 動態播放 Excel 文件中的數據

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

我能做些什么來完成這項工作? 該程序執行成功但顯示此錯誤
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: - 如果sh2.cell(r+1,c).valueNone (這相當於 Python 的 null),將拋出異常。

該值很可能包含None因為您正在循環拋出sh2.max_row+2的憤怒(您可能不需要 + 2

解決此問題的一種解決方案是使用if sh2.cell(r+1,c).value and...始終檢查 value is not null。 例如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")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM