Pandas`to_excel`设置字体名称

时间:2017-04-17 15:41:38

标签: python excel pandas xlsxwriter

是否可以使用pandas的excel writer设置字体名称?

这是我的尝试:

import pandas as pd
from pandas.io.excel import ExcelWriter

df = pd.DataFrame([[1,2,3],[4,5,6]])
writer = ExcelWriter("test.xlsx")
writer.set_font_name("Arial")  # this would be ideal, but no such method exists

format = writer.book.add_format({"font_name": "Arial"})
df.to_excel(writer)  # format is not applied. Need to pass `format` object somewhere

writer.close()

创建xlsxwriter.format.Format对象后,我在哪里可以传递它?

1 个答案:

答案 0 :(得分:5)

更新:使用类似于@miradulo's solution的解决方案,我们可以让它适用于不同版本的Pandas:

try:
    import pandas.io.formats.excel as fmt_xl     # version >= 0.20
except ImportError:
    try:
        import pandas.formats.format as fmt_xl   # 0.18 <= version < 0.20
    except ImportError:
        import pandas.core.format as fmt_xl      # version < 0.18

df = pd.DataFrame([[1,2,3],[4,5,6]], columns=list('abc'))

fmt_xl.header_style = None

writer = pd.ExcelWriter("d:/temp/test.xlsx")

df.to_excel(writer, index= False)

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

fmt = writer.book.add_format({"font_name": "Arial"})
worksheet.set_column('A:Z', None, fmt)
worksheet.set_row(0, None, fmt)

writer.save()

XlsxWriter文档:Working with Python Pandas and XlsxWriter