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

使用Pandas写入Excel时遭遇Unsupported Operation: truncate()错误求助

解决pandas写入Excel时的io.UnsupportedOperation: truncate错误

错误原因

  1. 格式兼容性问题:openpyxl引擎仅支持.xlsx/.xlsm格式,若目标文件为旧版.xls格式,使用mode='a'追加时会触发该错误——旧格式文件的底层文件句柄不支持truncate()操作。
  2. 文件结构异常:若Excel文件由非Excel工具生成、或已损坏,openpyxl无法正确解析并修改,保存阶段会触发truncate操作失败。
  3. 依赖版本bug:旧版openpyxl(v3.0以下)与pandas的组合,在使用if_sheet_exists='replace'参数时存在逻辑缺陷,导致保存时调用truncate失败。

解决办法

1. 强制使用标准xlsx格式

确保目标文件后缀为.xlsx,若原文件是.xls,先转换格式:

import os
import pandas as pd
from pandas import ExcelWriter

def convert_xls_to_xlsx(xls_path):
    if not xls_path.endswith('.xls'):
        return xls_path
    # 需安装xlrd==1.2.0(xlrd 2.0+不再支持xls格式)
    import xlrd
    wb = xlrd.open_workbook(xls_path)
    new_path = os.path.splitext(xls_path)[0] + '.xlsx'
    with ExcelWriter(new_path) as writer:
        for sheet_idx in range(wb.nsheets):
            sheet = wb.sheet_by_index(sheet_idx)
            data = sheet.get_rows()
            headers = next(data)
            df = pd.DataFrame(data, columns=[h.value for h in headers])
            df.to_excel(writer, sheet_name=sheet.name, index=False)
    return new_path

# 在touch_excel函数开头调用格式转换
file_path = convert_xls_to_xlsx(file_path)

2. 重写写入逻辑,规避mode='a'的问题

不使用pandas的追加模式,直接加载现有工作簿并修改:

import os
import pandas as pd
from openpyxl import load_workbook

def touch_excel(
        df: pd.DataFrame,
        file_path: str,
        sheet_name: str = "Sheet1",
        add_df: pd.DataFrame = None):
    """
    合并DataFrame并写入Excel文件
    Args:
        df: 主DataFrame
        file_path: Excel文件路径
        sheet_name: 工作表名称
        add_df: 待合并的额外DataFrame
    """
    if add_df is not None:
        df = pd.concat([df, add_df], ignore_index=True)

    try:
        if not os.path.exists(file_path):
            df.to_excel(file_path, sheet_name=sheet_name, index=False)
        else:
            # 加载现有工作簿
            book = load_workbook(file_path)
            with pd.ExcelWriter(file_path, engine='openpyxl') as writer:
                writer.book = book
                # 替换已存在的工作表
                if sheet_name in writer.book.sheetnames:
                    del writer.book[sheet_name]
                df.to_excel(writer, sheet_name=sheet_name, index=False)
                writer.save()
    except PermissionError:
        raise Exception("文件可能已打开,请关闭后重试。")

3. 更新依赖库到最新版

升级pandas和openpyxl,修复已知bug:

pip install --upgrade pandas openpyxl

4. 修复异常文件

若文件由第三方工具生成,手动用Excel打开并重新保存为标准.xlsx格式,再交由程序处理。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 20:25:10