3

Is it possible to set the font name with pandas' excel writer?

Here is my attempt:

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()

Where can I pass the xlsxwriter.format.Format object once it has been created?

gozzilli
  • 8,089
  • 11
  • 56
  • 87

1 Answers1

5

UPDATE: using a solution similar to @miradulo's solution we can make it working for different versions of 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 Docs: Working with Python Pandas and XlsxWriter

MaxU - stand with Ukraine
  • 205,989
  • 36
  • 386
  • 419