此代码段效果很好:
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')
现在我想将第一行(年份,金额)作为标题。
如何使用openpyxl执行此操作?
答案 0 :(得分:0)
只用熊猫来处理它(但看起来很困难),您也可以在 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")
答案 1 :(得分:0)
您可以通过更改字体颜色, 冻结第一行并将第一行标记为 print_title_rows
,将第一行标记为Header。为字体添加aRGB十六进制值
font =字体(color =“ FF0000”)
ws [“ A1”]。font =字体
ws [“ B1”]。font =字体
如果您尝试<冻结>冻结第一行(即第一行),然后将添加打印标题添加到第一行。 您可以通过设置工作表属性的 freeze_panes 和 print_title_rows 来实现此目的。
ws.freeze_panes =“ A2”
ws.print_title_rows ='1:1'
freeze_panes将冻结给定单元格上方的行,并且必须在插入某些数据之后调用。
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')