【问题标题】:Include a header from Excel in a for loop with openpyxl使用 openpyxl 在 for 循环中包含 Excel 中的标头
【发布时间】:2022-06-23 00:18:51
【问题描述】:

我试图在列中打印数据时包含标题。

问题

但是当我尝试时出现错误:

TypeError: 'int' 和 'str' 的实例之间不支持'

代码

def pm1():
    for cell in all_columns[1]:
        power = (cell.value)

        if x < power < y:
            print(f"{power}")
        else:
            print("Not steady")
pm1()

我知道您不能将字符串与操作值进行比较。

如何在整个列中循环时包含标题?

【问题讨论】:

  • power = float(cell.value) ?
  • 由于某种原因,出现错误,提示无法将字符串转换为浮动。
  • 好吧,然后清理您的输入。打印单元格值,您将看到单元格中无法转换为浮点数的内容。您可能需要单独处理空字符串。
  • 抱歉,我不确定这是什么意思。我对 python 还很陌生
  • 检查单元格是否包含数字。

标签: python openpyxl


【解决方案1】:

因此,您正在遍历一列的所有单元格,此处由第一列 all_columns[1] 给出。

假设每列的第一个单元格可能包含一个标题,其值为字符串类型 (type(cell.value) == str)。

那么你有可能:

  1. 鉴于每列(第 1 行)的第一个单元格是标题,请利用该位置
  2. 如果所有其他单元格都包含数值,您只能处理 str 值作为假定标题
def power_of(value):
    power = float(value)  # defensive conversion, some values might erroneously be stored as text in Excel
    if x < power < y:
        return f"{power}")
    return "Not steady"  # default return instead else


def pm1():
    for cell in all_columns[1]:
        if (cell.row == 1):   # assume the header is always in first row
            print(cell.value)  # print header
        else:
            print(power_of(cell.value))

pm1()

【讨论】:

    【解决方案2】:

    根据我从您的 cmets 中了解到的情况,这可能对您有用。

    def pm1():
    
        for cell in all_columns[1]:
            for thing in cell:
                # in openpyxl you can call on .row or .column to get the location of your cell
                # you said you wanted to print the header (row 1), a sting
                if thing.row == 1:
                    print(thing.value)
                else:
                    # you said that the values under the header will be a digit 
                    # so now you should be safe to set your variable and make a comparison
                    power = thing.value
        
                    if x < power < y:
                        print(f"{power}")
                    else:
                        print("Not steady")
    
    

    【讨论】:

    • 你应该在代码中解释你在做什么。可以在代码中使用 cmets。
    猜你喜欢
    • 2016-04-16
    • 2015-09-04
    • 2020-02-03
    • 2020-05-24
    • 1970-01-01
    • 2014-11-21
    • 1970-01-01
    • 2012-02-19
    • 1970-01-01
    相关资源
    最近更新 更多