Search code examples
pythonexcelrowheightopenpyxl

Python - Excel - Modify Specific Row Height with Openpyxl


I need to format the height of 2 rows in an excel workbook using openpyxl. There is only 1 sheet in the workbook. I managed to figure something out for formatting the width of the columns, but I can't seem to figure out how to do the row height.

I need to format row 1's height to 130, and row 2's height to 25 - all else to remain the default 15. This is the code I have for formatting the column width:

newFile = "MyWorkbook.xlsx"
wb = openpyxl.load_workbook(filename = newFile)        
worksheet = wb.active
for column in ascii_uppercase:
    if (column=="A"):
        worksheet.column_dimensions[column].width = 37
    elif (column=="B"):
        worksheet.column_dimensions[column].width = 37
    elif (column=="C"):
        worksheet.column_dimensions[column].width = 37
    elif (column=="D"):
        worksheet.column_dimensions[column].width = 130
    else:
        worksheet.column_dimensions[column].width = 15
   
wb.save(newFile)

I tried to translate this to work for row height, but it didn't seem to work - any help would be greatly appreciated.

for row in ascii_uppercase:
    if (row=="1"):
        worksheet.row_dimensions[row].height = 130
    elif (row-=="2"):
        worksheet.row_dimensions[row].height = 25
    else:
        worksheet.row_dimensions[row].height = 15

Solution

  • You're looping through ascii_uppercase and not finding the cases?

    UPDATE

    The height attribute expects integer values corresponding to the row numbers. You can try something like this:

    for row in range(worksheet.max_row):
        if (row == 1):
            worksheet.row_dimensions[row].height = 130
        elif (row == 2):
            worksheet.row_dimensions[row].height = 25
        else:
            worksheet.row_dimensions[row].height = 15