Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OpenPyXl: Mark row as heading

This snippet works fine:

from openpyxl import Workbook

data = [
    ['Year', 'Amount'],
    ['2016', '1000'],
    ['2017', '1300'],
    ['2018', '1500'],
]

wb = Workbook()
for row in data:
    wb.active.append(row)

wb.save('test.xlsx')

Now I would like to make the first row (Year, Amount) a heading.

How to do this with openpyxl?

like image 913
guettli Avatar asked Oct 27 '25 07:10

guettli


1 Answers

You can mark first row as Header by changing font color, freezing First row and making first row as print_title_rows

Adding aRGB hex values color to font

font = Font(color="FF0000")

ws["A1"].font = font
ws["B1"].font = font

link for style

If your trying to Freeze Top Row ie first row and add Add Print Titles to first row. You can achieve this by using setting freeze_panes and print_title_rows of worsheet properties.

ws.freeze_panes = "A2"

ws.print_title_rows='1:1'

freeze_panes will freeze rows above the given cell and must be call after some data has been inserted.

links for worksheet modules

print settings

from openpyxl import Workbook
from openpyxl.styles import Font
data = [
    ['Year', 'Amount'],
    ['2016', '1000'],
    ['2017', '1300'],
    ['2018', '1500'],
]

wb = Workbook()
for row in data:
    wb.active.append(row)
font = Font(color="FF0000")
ws = wb.active
ws.freeze_panes = "A2"
ws["A1"].font = font
ws["B1"].font = font
ws.print_title_rows = '1:1'
wb.save('test.xlsx')
like image 137
bkawan Avatar answered Oct 28 '25 20:10

bkawan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!