gpt4 book ai didi

python - Pandas `to_excel` 设置字体名称

转载 作者:太空宇宙 更新时间:2023-11-03 14:05:59 28 4
gpt4 key购买 nike

是否可以使用 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 对象创建后我可以在哪里传递它?

最佳答案

更新:使用类似于 @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

关于python - Pandas `to_excel` 设置字体名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43454635/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com