How to freeze entire header row in openpyxl?

22,574

Make sure cell isn't on row one - freeze_panes will freeze rows above the given cell and columns to the left.


Example:

from openpyxl import Workbook
wb = Workbook()
ws = wb.active
c = ws['B2']
ws.freeze_panes = c
wb.save('test.xlsx')

This will give you a blank worksheet with both row 1 and column A frozen.

Share:
22,574
Yudhistira Arya
Author by

Yudhistira Arya

Updated on November 09, 2021

Comments

  • Yudhistira Arya
    Yudhistira Arya over 1 year

    How to freeze entire header row in openpyxl? So far I can only freeze the column:

    # only freeze the column (freeze vertically)
    cell = ws.cell('{}{}'.format(col, row_idx+1))  
    worksheet.freeze_panes = cell
    
  • mvbentes
    mvbentes about 6 years
    Or you could just do wb["Sheet_name"].freeze_panes = "B2"
  • rosch
    rosch over 5 years
    Probably obvious: use 'A2' instead of 'B2' to only freeze the header row.
  • Chris
    Chris over 5 years
    @mvbentes You should consider posting this as an answer.
  • Denis
    Denis about 4 years
    A suggestion to complete Paul's solution: freeze panes only after inserting some data. Otherwise, the freezed row will be empty if you insert data with an ws.append([…]).
  • run_the_race
    run_the_race about 4 years
    @mvbentes comment of wb["Sheet_name"].freeze_panes = "B2" will work in write only mode too.