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

读取含图片的Excel文件遇XML无效错误,求忽略损坏样式表方案

解决读取含图片Excel时样式表损坏的问题

针对你遇到的ValueError: Unable to read workbook: could not read stylesheet错误,以下是几种可行的解决思路:

方法1:切换到openpyxl引擎并调整读取参数

pandas默认的xlrd引擎对损坏样式表的兼容性较差,改用openpyxl引擎并启用只读模式,通常能绕过样式表解析错误:

import pandas as pd

# 用openpyxl引擎,只读模式读取
df = pd.read_excel('/content/MYFILE.xlsx', engine='openpyxl', read_only=True)

如果仍有问题,可以尝试结合data_only=True参数(只读取单元格值,忽略公式和样式):

from openpyxl import load_workbook
import pandas as pd

wb = load_workbook('/content/MYFILE.xlsx', read_only=True, data_only=True)
sheet = wb.active
df = pd.DataFrame(sheet.values)

方法2:手动移除损坏的样式表文件

Excel本质是ZIP压缩包,直接删除其中的样式表文件可以绕过解析错误:

import zipfile
import os
import shutil
import pandas as pd

def fix_corrupted_excel(input_path, output_path):
    # 创建临时目录
    temp_dir = 'temp_excel'
    os.makedirs(temp_dir, exist_ok=True)
    
    # 解压Excel文件
    with zipfile.ZipFile(input_path, 'r') as zip_ref:
        zip_ref.extractall(temp_dir)
    
    # 删除样式表文件
    styles_path = os.path.join(temp_dir, 'xl', 'styles.xml')
    if os.path.exists(styles_path):
        os.remove(styles_path)
    
    # 重新打包成Excel文件
    with zipfile.ZipFile(output_path, 'w', zipfile.ZIP_DEFLATED) as zip_ref:
        # 遍历临时目录,添加所有文件到压缩包
        for root, dirs, files in os.walk(temp_dir):
            for file in files:
                file_path = os.path.join(root, file)
                # 计算相对路径,确保压缩包结构正确
                arcname = os.path.relpath(file_path, temp_dir)
                zip_ref.write(file_path, arcname)
    
    # 清理临时目录
    shutil.rmtree(temp_dir)
    return output_path

# 使用示例
fixed_file = fix_corrupted_excel('/content/MYFILE.xlsx', '/content/FIXED_MYFILE.xlsx')
df = pd.read_excel(fixed_file)

方法3:用Excel自身修复文件(Windows环境)

如果是Windows系统,可以通过win32com调用Excel自动打开并保存文件,利用Excel的内置修复功能:

import win32com.client as win32
import pandas as pd

def repair_excel(input_path, output_path):
    excel = win32.gencache.EnsureDispatch('Excel.Application')
    excel.Visible = False
    # 打开文件时启用修复
    wb = excel.Workbooks.Open(input_path, CorruptLoad=1)
    wb.SaveAs(output_path)
    wb.Close()
    excel.Quit()
    return output_path

# 使用示例
repaired_file = repair_excel('C:/path/to/MYFILE.xlsx', 'C:/path/to/REPAIRED_MYFILE.xlsx')
df = pd.read_excel(repaired_file)

这些方法都能绕过样式表损坏的问题,无需手动删除图片即可读取Excel内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 11:29:59