openpyxl 和迭代 + 更改特定单元格 question/seeking 资源

openpyxl and iteration + alter specific cells question/seeking resource

这里 python 很新。请在使用 openpyxl 方面需要一些帮助!这是我 self-learning 旅程中的个人项目。我正在寻找一种资源来向我展示如何在 pip3 openpyxl 中执行以下操作:

我有一个 class,它有一个用作唯一标识符的变量。这是我的 excel 工作簿中的第一列。我想做什么:

我想向电子表格添加新 ID。这意味着,首先,我只需要遍历第一列并确保新的唯一标识符不存在。我相信以下代码可以成功完成此迭代:

for row in sheet.iter_rows('A{}:A{}'.format(sheet.min_row,sheet.max_row)):

然后,如果不存在唯一标识符,这意味着 ID 尚未包含在数据集中,我想将该 ID 及其关联的 class 值添加到新行中的数据集。我认为以下行可以做到这一点,在 header 行的正下方插入一个新行:

sheet.insert_rows(idx=2)

然后我在下面编写代码,用适当的值填充该行中的其余单元格。

否则,如果唯一标识符已经存在,我想使用包含该标识符和关联的 class 值的行中的 一些 数据,做一些重新计算 those 个单元格,然后更新行中 other values/cells 的 some , 覆盖旧值。这是我特别需要帮助的。

根据我在其他地方看到的东西,这是我的想法,将所有内容放在一起:

for row in sheet.iter_rows('A{}:A{}'.format(sheet.min_row,sheet.max_row)):
    if fin.fin != row:                  

fin 是唯一的 ID,它是每个案例的名称,也是存储在 class 中的一个属性。我还想知道 != row 是否可以在这里工作,或者我是否需要像 row[0] 一样进行索引,或者是否应该使用 row.value?

        sheet.insert_rows(idx=2)
        sheet["A2"] = fin.fin     #setting cell A2 = unique id attribute of my class instance
        sheet["B2"] = fin.kgs     #setting cell B2 = kgs attribute of my class instance
        sheet["F2"] = fin.kgs_to_lbs() #setting cell F2 to module output converting kgs to lbs
    else:
        sheet['B{}'.format(row)] = fin.kgs.format(row) #if the id is not unique, change value in column B of that row
        sheet['F{}'].format(row) = fin.kgs_to_lbs.format(row) #if the id is not unique, change value in column F of that row

希望这很清楚。让我知道是否有任何问题。我正在寻找一些示例代码或对有用资源的参考!

您的代码存在一些问题。在妈妈网上,您的代码正在遍历 A 列中的单元格,并检查单元格对象是否等于您的属性 fin.fin,我假设它是字符串或整数 (?)。因为它们不是 总是FALSE 从而在行 2.

之上创建一个新行

因此,您要回答的问题实际上是 - fin.fin 是否已存在于 A 列中?。为此,您只需获取 A 列中的值列表并检查其中是否包含 fin.fin,我们将使用 list comprehension 来构建它:

known_identifiers = [cell.value for cell in ws['A']]  # Creating a list of all known identifiers from column A

if fin.fin is not in known_identifiers:
    # Special identifier is not in the Excel file add it and data

    sheet.insert_rows(idx=2)

    sheet["A2"] = fin.fin  # setting cell A2 = unique id attribute of my class instance
    sheet["B2"] = fin.kgs  # setting cell B2 = kgs attribute of my class instance
    sheet["F2"] = fin.kgs_to_lbs()  #setting cell F2 to module output converting kgs to lbs


else:
    # Identifier found, Change data in specific columns.

   row = known_identifiers.index(fin.fin)+1  # Row is the same as the item list index+1 (As lists start from 0 and rows from 1)         
   sheet[f"B{row}"] = fin.kgs.format(row)  # Not sure why you need `format` here but it's your class
   sheet[f"F{row}"] = fin.kgs_to_lbs.format(row) # Same

请注意 int(identifier) != str(identifier),因此请确保您正在检查相同类型的变量,如果需要,请转换一个或另一个。此外,我在我的代码中使用了 f-strings,因为我认为它会生成更清晰的代码,您可以阅读这些 - Here.