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

时间:2014-06-05 16:32:23

标签: python io pandas xlsx xlsxwriter

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

然而,我无法找到一种方法来对熊猫方法做同样的事情。只是传递一个带有列名和样式的字典将是最直观的。

有没有办法这样做?

4 个答案:

答案 0 :(得分:10)

  

有没有办法这样做

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

但是,即使是XlsxWriter目前也不支持在添加数据后格式化单元格。它位于TODO list

<强>更新

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

请参阅Working with Python Pandas and XlsxWriter

答案 1 :(得分: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

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

版本&lt; 0.20.0 pandas.formats.format.header_style

版本&lt; 0.18.0 pandas.core.format.header_style

答案 2 :(得分:4)

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

&#13;
&#13;
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)
&#13;
&#13;
&#13;

答案 3 :(得分:1)

下一版Pandas(2.0)将包含使用openpyxl将样式化DataFrames直接导出到Excel的实验性支持:http://pandas-docs.github.io/pandas-docs-travis/style.html#Export-to-Excel