在使用XlsxWriter导出到pandas中的'xlsx'时应用样式

Nik*_*ita 11 python io xlsx pandas xlsxwriter

我使用pandas的.to_excel方法将DataFrame写为Excel工作簿.当索引单元合并时,即使对于多索引DataFrame,这也很好用.当使用纯XlsxWriter时,我可以将格式应用于单元格,这也很好用.

但是我找不到用pandas方法做同样的方法.只是传递一个带有列名和样式的字典将是最直观的.

有没有办法这样做?

jmc*_*ara 10

有没有办法这样做

目前没有.在Pandas中没有像格式化机制那样格式化Excel输出(除了一些硬编码格式).

但是,即使是XlsxWriter当前也不支持在添加数据后格式化单元格.它在TODO列表中.

更新:

作为一种解决方法,我建议获取对底层工作簿和工作表的引用,并使用Pandas数据帧和XlsxWriter格式中的相同数据覆盖您希望格式化的任何单元格.

请参阅使用Python Pandas和XlsxWriter.


Tim*_*ann 7

如果您只想设置标题样式,则可以进行修改pandas.io.formats.excel.header_style.当然,这不是一般的解决方案,但对于常见的用例来说,这是一个简单的解决方法.

import pandas.core.format
header_style_backup = pandas.io.formats.excel.header_style
try:
    pandas.io.formats.excel.header_style = {"font": {"bold": True},
                                       "borders": {"top": "thin", "right": "thin", "bottom": "thin", "left": "thin"},
                                       "pattern": {"pattern": "solid", "fore_colour": 26},
                                       "alignment": {"horizontal": "center", "vertical": "top"}}
    df.to_excel(writer, sheet_name=sheetname, startrow=table_startrow)
finally:
    pandas.formats.format.header_style = header_style_backup
Run Code Online (Sandbox Code Playgroud)

注意: header_style的位置在先前的pandas版本中已经多次更改.对旧版本使用以下内容:

版本<0.20.0 pandas.formats.format.header_style

版本<0.18.0 pandas.core.format.header_style


chr*_*isp 5

以下方法允许我在数据框索引和列名上使用 xlsxwriter 格式(尽管我不能保证它的有效性):

import pandas as pd
import xlsxwriter as xl

# remove pandas header styles
# this avoids the restriction that xlsxwriter cannot
# format cells where formatting was already applied
pd.core.format.header_style = None

# write dataframe to worksheet
writer = pd.ExcelWriter(sumfile, engine='xlsxwriter')
df.to_excel(writer, sheet_name='test')

# create desired xlsxwriter formats
workbook  = writer.book
worksheet = writer.sheets['test']
header = workbook.add_format({'bold': True})
index = workbook.add_format({'align': 'left'})

# apply formats to header and index
worksheet.set_row(0, None, header)
worksheet.set_column(0,0, None, index)
Run Code Online (Sandbox Code Playgroud)