OpenPyXl: Mark row as heading

怎甘沉沦 提交于 2021-01-27 23:33:57

问题


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?


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



回答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")


来源:https://stackoverflow.com/questions/55041209/openpyxl-mark-row-as-heading

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!