pandas xlsxwriter, format header

我只是一个虾纸丫 提交于 2019-11-27 18:11:48

I think you need first reset default header style, then you can change it:

pd.core.format.header_style = None

All together:

import pandas as pd

data = pd.DataFrame({'test_data': [1,2,3,4,5]})
writer = pd.ExcelWriter('test.xlsx', engine='xlsxwriter')

pd.core.format.header_style = None

data.to_excel(writer, sheet_name='test', index=False)

workbook  = writer.book
worksheet = writer.sheets['test']

font_fmt = workbook.add_format({'font_name': 'Arial', 'font_size': 10})
header_fmt = workbook.add_format({'font_name': 'Arial', 'font_size': 10, 'bold': True})

worksheet.set_column('A:A', None, font_fmt)
worksheet.set_row(0, None, header_fmt)

writer.save()

Explaining by jmcnamara, thank you:

In Excel a cell format overrides a row format overrides a column format.The pd.core.format.header_style is converted to a format and is applied to each cell in the header. As such the default cannot be overridden by set_row(). Setting pd.core.format.header_style to None means that the header cells don't have a user defined format and thus it can be overridden by set_row().

EDIT: In version 0.18.1 you have to change

pd.core.format.header_style = None

to:

pd.formats.format.header_style = None

EDIT: from version 0.20 this changed again

import pandas.io.formats.excel
pandas.io.formats.excel.header_style = None

thanks krvkir.

An update for anyone who comes across this post and is using Pandas 0.20.1.

It seems the required code is now

import pandas.io.formats.excel
pandas.io.formats.excel.header_style = None

Apparently the excel submodule isn't imported automatically, so simply trying pandas.io.formats.excel.header_style = None alone will raise an AttributeError.

In pandas 0.20 the solution of the accepted answer changed again.

The format that should be set to None can be found at:

pandas.io.formats.excel.header_style

for pandas 0.24:

The below doesn't work anymore:

import pandas.io.formats.excel
pandas.io.formats.excel.header_style = None

Instead, use the following pseudo code to be in self-control and future proof:

# [1] write df to excel as usual
writer = pd.ExcelWriter(path_output, engine='xlsxwriter')
df.to_excel(writer, sheet_name, index=False)

# [2] do formats for other rows and columns first

# [3] create a format object for the header: headercellformat

# [4] write to the header row **one cell at a time**, with columnname and format
for columnnum, columnname in enumerate(list(df.columns)):
    worksheet.write(0, columnnum, columnname, headercellformat)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!