python 错误:属性错误:“str”对象没有属性“row”

kknvjkwl  于 2023-04-04  发布在  Python
关注(0)|答案(1)|浏览(469)

我有代码:

def add_to_database(object_name, value):
    workbook = openpyxl.load_workbook(DATABASE_FILE)
    worksheet = workbook[DATABASE_SHEET]
    object_row = None
    for row in worksheet.iter_rows(min_row = 1, max_row = worksheet.max_row + 1, values_only = True):
        if row[0] == object_name:
            object_row = row
            break
    if object_row:
        worksheet.cell(row = object_row[0].row, column = 2).value += value
    else:
        last_row = worksheet.max_row
        worksheet.cell(row = last_row, column = 1).value = object_name
        worksheet.cell(row = last_row, column = 2).value = value
    workbook.save(DATABASE_FILE)
    workbook.close()

我得到一个错误:属性错误:“str”对象在行上没有属性“row”:工作表.cell(row = object_row[0].row,column = 2).value += value
我哪里做错了?

mdfafbf1

mdfafbf11#

你试图从一个字符串中获取行值,而这个字符串没有行值,你还需要创建一个循环来考虑行号,这样才能做到这一点。

import openpyxl

DATABASE_FILE = "your_database_file.xlsx"
DATABASE_SHEET = "your_database_sheet"

def add_to_database(object_name, value):
    workbook = openpyxl.load_workbook(DATABASE_FILE)
    worksheet = workbook[DATABASE_SHEET]
    object_row_num = None
    for row_num, row in enumerate(worksheet.iter_rows(min_row=1, max_row=worksheet.max_row, values_only=True), start=1):
        if row[0] == object_name:
            object_row_num = row_num
            break
    if object_row_num:
        worksheet.cell(row=object_row_num, column=2).value += value
    else:
        last_row = worksheet.max_row + 1
        worksheet.cell(row=last_row, column=1).value = object_name
        worksheet.cell(row=last_row, column=2).value = value
    workbook.save(DATABASE_FILE)
    workbook.close()

未经测试,但 * 应该 * 工作。Lmk如果它不。

相关问题