Question about creating an excel file in Python


Considering I have this code. (Creating a new excel file)

import openpyxl
wb = openpyxl.Workbook()
sheet = wb[‘Sheet’]
sheet.title = ‘Hobbies’“test.xlsx”)

… I’m trying to figure out this lines:

sheet = wb[‘Sheet’]
sheet.title = ‘Hobbies’

what does it means…? sheet = wb[‘Sheet’]

wb is an instance of Workbook() class.

sheet is an instance too ? because in the command below we then use it
to call title method. what the meaning of the square brackets with the Sheet quotation marks…?

I also saw something similar in tkinter module to change the font parameter,
after creating an instance to change the text of the instance attribute. like that …
it’s the same like my first example?

lable1 = tkinter.Label(frame1, font=(“ariel”,11))
clk1.grid(row=0, column=0, padx=8)

lable1[‘text’] = “new label”

can someone explain it to me more deeply ? I’m confusing with it …

Thanks in advance,

That’s a dictionary access. The thing between the square brackets is the key. A simple example of a dictionary is a phone book: The keys are names, and the values phone numbers. What sheet = wb['Sheet'] does is: Get the element with the label “Sheet” from wb, and store it in the variable sheet. You can also do the reverse (like d['abc'] = 12345) to add or change a dictionary entry. I’d recommend you take a look at the section on dictionaries in the Python Tutorial for a deeper explanation.

sheet.title = 'Hobbies' is a normal variable assignment, with the slight twist that the variable being assigned to is the title attribute of the sheet object.

1 Like