AttributeError: 'tuple' object has no attribute 'value' PYTHON TO EXCEL

AttributeError: 'tuple' object has no attribute 'value' PYTHON TO EXCEL

我目前正在尝试使用 Python3 和 openpyxl 将数据写入 excel 电子表格。我已经想出了在分配一个值时如何做到这一点,但由于某种原因,当我引入一个 For 循环时它给了我一个错误。该程序最终将用于过滤 python 字典并打印出 python 字典中的键和值。现在,我只是想创建一个循环,该循环将在电子表格中为字典中列出的每个键(不包括嵌套键)输入一个随机整数。如果有人可以帮助我确定为什么会出现此错误,将不胜感激。提前致谢!

# Writing Dictionary to excel spreadsheet
import openpyxl
import random

wb = openpyxl.load_workbook("ExampleSheet.xlsx")
sheet = wb.get_sheet_by_name("Sheet1")

sheet["B1"].value = "Price" #This works and assigns the B1 value to "price" in the spreadsheet

my_dict = {'key': {'key2' : 'value1', 'key3' : 'value2'} 'key4' : {'key5' : 'value3', 'key6' : 'value4'}} #an example dictionary

n = len(my_dict)
  for i in range(0,n): 
    sheet['A'+ str(i)].value = random.randint(1,10) #This does not work and gives an error

wb.save('ExampleSheet.xlsx')

OUTPUT >>> AttributeError: 'tuple' object has no attribute 'value'

pyxl 的第一列是基于 one 的,因此如果您修改循环以超过范围 (1,n),您的问题应该得到解决

在您的代码中使用 .format(i) 而不是 string + str(i) 可能效果很好!

顺便说一句,你的变量 my_dict 得到一个错误。

例如:

for i in range(10):
    sheet['A{}'.format(i)].value = 'xx'