Skip to content Skip to sidebar Skip to footer

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 ro

Solution 1:

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')

Solution 2:

just use pandas to deal with it,(but looks difficult),you can also see the example in https://openpyxl.readthedocs.io/en/stable/pandas.html

from openpyxl.utils.dataframe import dataframe_to_rows
wb = Workbook()
ws = wb.active

for r in dataframe_to_rows(df, index=True, header=True):
    ws.append(r)
wb = Workbook()
ws = wb.active

for r in dataframe_to_rows(df, index=True, header=True):
    ws.append(r)

for cell in ws['A'] + ws[1]:
    cell.style = 'Pandas'

wb.save("pandas_openpyxl.xlsx")

Post a Comment for "OpenPyXl: Mark Row As Heading"