How to set a font and size to save information in pandas?

huangapple go评论127阅读模式
英文:

How to set a font and size to save information in pandas?

问题

需要将提取的数据以相同的格式保存,字体使用Arial,字号为12。

目前代码的字体和字号没有遵循统一的模式。

我尝试使用utf-8命令,但没有成功。

df_conversas = pd.DataFrame({'Nomes': nomes_conversas})

df_conversas.to_excel('conversas.xlsx', encoding='utf-8', index=False)
英文:

I need to save the extracted data in the same format, Arial font size 12.

Currently the code does not follow a pattern of font and size.

I tried using the utf-8 command and it didn't work.

df_conversas = pd.DataFrame({'Nomes': nomes_conversas})

df_conversas.to_excel('conversas.xlsx', encoding='utf-8', index=False)

答案1

得分: 1

你可以使用ExcelWriter与[tag:xlsxwriter] engine

df_conversas = pd.DataFrame({"Nomes": ["foo", "bar", "baz", "qux"]})

with pd.ExcelWriter("conversas.xlsx", engine="xlsxwriter") as writer:
    df_conversas.to_excel(writer, sheet_name="Sheet1", index=False)

    workbook = writer.book
    workbook.formats[0].set_font_name("Arial")
    workbook.formats[0].set_font_size(12)
    
    header_format = workbook.add_format(
        {"font_name": "Arial", "font_size": 12, "bold": True}
    )

    writer.sheets["Sheet1"].write(0, 0, "Nomes", header_format)

    # 如果你有多列,可以使用以下代码:
    # for idx, col in enumerate(df_conversas.columns):
    #     writer.sheets["Sheet1"].write(0, idx, col, header_format)

输出:

How to set a font and size to save information in pandas?

英文:

You can use ExcelWriter with an [tag:xlsxwriter] engine :

df_conversas = pd.DataFrame({"Nomes": ["foo", "bar", "baz", "qux"]})

with pd.ExcelWriter("conversas.xlsx", engine="xlsxwriter") as writer:
    df_conversas.to_excel(writer, sheet_name="Sheet1", index=False)

    workbook = writer.book
    workbook.formats[0].set_font_name("Arial")
    workbook.formats[0].set_font_size(12)
    
    header_format = workbook.add_format(
        {"font_name": "Arial", "font_size": 12, "bold": True}
    )

    writer.sheets["Sheet1"].write(0, 0, "Nomes", header_format)

    #if you have more than a column, use this :
    #for idx, col in enumerate(df_conversas.columns):
    #    writer.sheets["Sheet1"].write(0, idx, col, header_format)

Output :

How to set a font and size to save information in pandas?

huangapple
  • 本文由 发表于 2023年5月15日 02:10:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/76249000.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定