OpenPyXl:将行标记为标题 [英] OpenPyXl: Mark row as heading
问题描述
此代码段工作正常:
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')
现在我想将第一行(Year, Amount)作为标题.
Now I would like to make the first row (Year, Amount) a heading.
如何使用 openpyxl 做到这一点?
How to do this with openpyxl?
推荐答案
您可以通过更改字体颜色、 冻结第一行并制作第一行来将第一行标记为标题作为 print_title_rows
You can mark first row as Header by changing font color, freezing First row and making first row as print_title_rows
将 aRGB 十六进制值颜色添加到字体
Adding aRGB hex values color to font
font = Font(color="FF0000")
font = Font(color="FF0000")
ws["A1"].font = 字体
ws["B1"].font = font
ws["A1"].font = font
ws["B1"].font = font
如果您尝试冻结顶行,即第一行并将打印标题添加到第一行.您可以通过设置工作表属性的freeze_panes 和print_title_rows 来实现这一点.
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.freeze_panes = "A2"
ws.print_title_rows='1:1'
ws.print_title_rows='1:1'
freeze_panes 将冻结给定单元格上方的行,并且必须在插入一些数据后调用.
freeze_panes will freeze rows above the given cell and must be call after some data has been inserted.
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')
这篇关于OpenPyXl:将行标记为标题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!