0

I am currently trying to write data to an excel spreadsheet using Python3 and openpyxl. I have figured out how to do it when assigning one single value, but for some reason when I introduce a For loop it is giving me an error. This program will eventually be used to filter through a python dictionary and print out the keys and values from the python dictionary. For now, I am just trying to create a loop that will input a random integer in the spreadsheet for every key listed in the dictionary (not including nested keys). If anyone can help me determine why this error is coming up it would be much appreciated. Thanks in advance!

# 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'
1
  • use ws.iter_rows(min_col=1, max_col=1) to avoid these kind of problems. Commented Jun 18, 2020 at 11:58

2 Answers 2

1

The first column of pyxl, is one based, so if you modify your loop to go over range(1,n) your issues should be resolved

Sign up to request clarification or add additional context in comments.

2 Comments

That's it! Thank you
hm, looks like ws['A0'] returns a column rather than raising an exception. This is a bug.
1

Using .format(i) instead of string + str(i) in ur code may work well!

BTW, ur var my_dict get an error .

eg:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.