【发布时间】:2020-10-07 22:50:24
【问题描述】:
我目前正在尝试使用 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'
【问题讨论】:
-
使用
ws.iter_rows(min_col=1, max_col=1)来避免此类问题。
标签: excel for-loop openpyxl attributeerror python-3.8