You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Pandas 2.0+版本如何保存xls格式文件?

现代Pandas版本中保存xls格式文件的方法

现代Pandas(如2.0及以上版本)已移除对xlwt库的默认依赖,直接尝试保存.xls文件时会触发ValueError: No engine for filetype: 'xls'错误,无论是否显式指定engine='xlwt'都会出现该问题。以下是两种可行的解决方法:

方法一:手动安装xlwt库继续使用

Pandas只是不再默认包含xlwt,你仍可手动安装该库,之后就能通过指定engine='xlwt'正常保存xls文件:

  1. 安装xlwt:
pip install xlwt
  1. 示例代码:
import pandas as pd

def create_excel_files():
    # 构造示例数据
    df1 = pd.DataFrame(
        {
            "A": ["This is the first sentence.", "This is the second sentence."],
            "B": ["This is a third sentence.", "This is a fourth sentence."],
        }
    )

    df2 = pd.DataFrame(
        {
            "A": ["This is from sheet 2.", "Another sentence from sheet 2."],
            "B": ["More content here.", "Final sentence from sheet 2."],
        }
    )

    # 保存为xls文件
    with pd.ExcelWriter("example.xls", engine='xlwt') as writer:
        df1.to_excel(writer, sheet_name="Sheet1", index=False)
        df2.to_excel(writer, sheet_name="Sheet2", index=False)
    print("Created example.xls")

create_excel_files()

方法二:使用xlwings(需本地安装Excel)

如果你的设备上安装了Excel,可以使用xlwings库,它依赖本地Excel环境完成xls文件的保存:

  1. 安装xlwings:
pip install xlwings
  1. 示例代码:
import pandas as pd
import xlwings as xw

def create_excel_files():
    df1 = pd.DataFrame(
        {
            "A": ["This is the first sentence.", "This is the second sentence."],
            "B": ["This is a third sentence.", "This is a fourth sentence."],
        }
    )

    df2 = pd.DataFrame(
        {
            "A": ["This is from sheet 2.", "Another sentence from sheet 2."],
            "B": ["More content here.", "Final sentence from sheet 2."],
        }
    )

    # 借助xlwings保存xls
    with xw.App(visible=False) as app:
        wb = app.books.add()
        # 写入第一个工作表
        wb.sheets["Sheet1"].range("A1").options(index=False).value = df1
        # 添加第二个工作表并写入数据
        wb.sheets.add("Sheet2")
        wb.sheets["Sheet2"].range("A1").options(index=False).value = df2
        # 保存为xls格式
        wb.save("example.xls")
        wb.close()
    print("Created example.xls")

create_excel_files()

注意事项

  • xlwt仅支持Excel 97-2003格式(.xls),单工作表最大支持65536行,对复杂格式的支持有限。
  • xlwings依赖本地Excel,Windows和macOS可直接使用,Linux需额外配置Excel兼容环境。

内容的提问来源于stack exchange,提问作者jss367

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 01:37:02