I have code:
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()
I get an error: AttributeError: 'str' object has no attribute 'row' on the line: worksheet.cell(row = object_row[0].row, column = 2).value += value
What am I doing wrong?
You're trying to get the row value from a string, something that doesn't have a row value. Also you'll want to create a loop that takes the row number into account to be able to do this.
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()
Untested, but should work. Lmk if it doesn't.