TypeError: expected <class ‘openpyxl.styles.fills.Fill‘>

本文讲述了在使用openpyxl处理Excel文件时遇到的因<fill/>节点引发的异常,通过修改styles.xml文件并替换掉该节点,解决了不支持的转换问题,确保了正常读写Excel文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

excel本质是一堆xml的zip文件, 这个异常是由于遇到了 `<fill/>`的节点,然后openpyxl不处理

class Fill(Serialisable):

    """Base class"""

    tagname = "fill"

    @classmethod
    def from_tree(cls, el):
        children = [c for c in el]
        if not children:
            return  # 这里返回None
        child = children[0]
        if "patternFill" in child.tag:
            return PatternFill._from_tree(child)
        return super(Fill, GradientFill).from_tree(child)


#--------------------------

def _convert(expected_type, value):
    """
    Check value is of or can be converted to expected type.
    """
    if not isinstance(value, expected_type):
        try:
            value = expected_type(value) # Fill 不支持__init__报错
        except:
            raise TypeError('expected ' + str(expected_type))
    return value

我的解决方式

reader = ExcelReader(f'{table}.xlsx')

def new_read(read):
    def inner(file):
        r = read(file)
        if file == 'xl/styles.xml':
            r = r.replace(b'<fill/>', b'')
        return r

    return inner

reader.archive.read = new_read(reader.archive.read)
reader.read()
reader.wb.save(f'{table}.xlsx')

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值