根据 pandas 文档,可以使用
df.style.map(lambda v: "@").to_excel()
将数字格式(Excel 术语)应用于导出的表。您可以指定 “文本” 数字格式,以代替默认使用的 “常规” 数字格式,以防止进入“编辑”模式时数字更改为日期(Excel 中的快捷键 F2
) ),然后按 Enter
。
使用
df.style.map(...)
的解决方案很好,但我有兴趣使用 engine_kwargs
1:
有没有办法使用 engine_kwargs
的 to_excel()
参数而不是
df.style.map(...)
来应用 "Text"数字格式?最好的答案是使用 openpyxl 作为引擎,但如果不可能,使用 xlsxwriter 作为引擎也是可以接受的。我不是在寻找使用
pd.ExcelWriter()
的解决方案,因为这是 已经有详细记录了。
这是
df.style.map(...).to_excel()
的示例:
import pandas as pd
df = pd.DataFrame([["23-3", "21-1"],
["8-5", "6-7"]], columns=["A", "B"])
# @ is the number format code of excel for Text.
df.style.map(lambda v: "number-format: @").to_excel(r"test.xlsx")
1增加可读性。
截至本答案之日,这似乎不可能:
来自文档:“XlsxWriter 支持多个 Workbook() 构造函数选项,例如 strings_to_urls()。这些也可以应用于 Pandas 使用 engine_kwargs 关键字创建的 Workbook 对象。”
df.to_excel(
r"test.xlsx",
engine="xlsxwriter",
engine_kwargs={"options": {"strings_to_urls": True}},
)
唉,没有用于格式化单元格的构造函数选项。
engine_kwargs
的使用有点不同,Workbook()构造函数支持的参数仅限于write_only
和iso_dates
:
df.to_excel(
r"test.xlsx",
engine="openpyxl",
engine_kwargs={"iso_dates": True},
)
所以,这也不是一个选择。