how can i set a value for X amount of cells in a worksheet?

Question:

i am reading the automate the boring stuff with python and wanted to modify one of the code used in the book. im trying to set a font for a range of cells and give those cells a value. but i keep getting a error

This is the code that i am trying:

import openpyxl as xl
from openpyxl.styles import Font 

wb = xl.Workbook()
sheet = wb["Sheet"]

italic24Font = Font(size=18, italic = True) # creating a font type, this returns a font object

for rowNum in range(1,100):
  cell = sheet.cell(row=rowNum, column=1)
  sheet[cell].font = italic24Font
  sheet[cell] = "what is happing?"

wb.save("idk.xlsx")

Error that i get:

Traceback (most recent call last):
  File "c:UsersJODesktopAutomate the boaring stuffChapter_13_Excelprojectsothertesting.py", line 12, in <module>
 sheet[cell].font = italic24Font
  File "C:UsersJOAppDataLocalPackagesPythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0LocalCachelocal-packagesPython310site-packagesopenpyxlworksheetworksheet.py", line 290, in __getitem__    min_col, min_row, max_col, max_row = range_boundaries(key)
  File "C:UsersJOAppDataLocalPackagesPythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0LocalCachelocal-packagesPython310site-packagesopenpyxlutilscell.py", line 133, in range_boundaries    
m = ABSOLUTE_RE.match(range_string)
TypeError: expected string or bytes-like object
Asked By: Mr.IDK

||

Answers:

You’re not accessing the cell correctly. You could access the first cell with sheet["A1"], but since you already have a reference to the cell, just change the font directly on the cell rather than via the sheet. You can also set the cell’s value with sheet.cell().

import openpyxl as xl
from openpyxl.styles import Font 

wb = xl.Workbook()
sheet = wb["Sheet"]

italic24Font = Font(size=18, italic = True) # creating a font type, this returns a font object

for rowNum in range(1,100):
  cell = sheet.cell(row=rowNum, column=1, value="what is happing?")
  cell.font = italic24Font
  
wb.save("idk.xlsx")
Answered By: Michael Ruth
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.