[Python Debugging] IndexError: list index out of range when Using Openpyxl
Error
I was working on my mini project called Schedulize, and an error occured while loading a workbook using openpyxl.
def create_excel_file(self):
wb = load_workbook(self.file_path) # IndexError: list index out of range
ws = wb.active
ws['A1'] = f"{self.duty_date.year} {self.duty_date.month}"
ws.column_dimensions['A'].width = 25
self.fill_in_dates(wb, ws)
self.fill_in_people(wb, ws)
wb.save(self.file_path)
At first, I had no idea what the error meant because it said that list index is out of range. My code was just to load a workbook (excel file) and modify it, so it had nothing to do with lists. After googling and asking chatGPT, I found out that it was a problem with styling. In my case, I set the cell width to 25 by doing this: ws.column_dimensions['A'].width = 25
. However, the cell width I set in my excel file was much bigger than 25. So, there was a crash. Furthermore, I did not make it center-align in my code, but I did center-align in the excel file that I’m loading, so there was a crash as well.
Solution
I left the excel file with no changes. I did not center-align the cell, and I also did not modify the cell width. After all that, IndexError: list index out of range
did not occur.