解决pandas写入excel时的ValueError: All strings must be XML compatible报错

报错内容:

ValueError: All strings must be XML compatible: Unicode or ASCII, no NULL bytes or control characters

报错背景

用pands批量写入excel文件,发生编码报错。检索了很多方案,都不能解决。

导致报错的原因是存在违法字符,不符合 XML 的解析规则。pandas写入应该是调用了xml的解析方法,所以这里也要符合xml的字符规则。

很多方法都是针对自己任务中遇到的特定违法字符进行的替换操作,不具备一般性。所以这里列出了一个最终解法------逐个字符的判断是否符合xml编译规则,只保留符合规则的编码。

最终代码

python 复制代码
def valid_xml_char_ordinal(c):
    codepoint = ord(c)
    # conditions ordered by presumed frequency
    return (
        0x20 <= codepoint <= 0xD7FF or
        codepoint in (0x9, 0xA, 0xD) or
        0xE000 <= codepoint <= 0xFFFD or
        0x10000 <= codepoint <= 0x10FFFF
        )


def wash_data(text):
    cleaned_string = ''.join(c for c in text if valid_xml_char_ordinal(c))
    return cleaned_string

text = "xxx"
text = wash_data(text)  # 完成清洗

参考

1\] [在python中过滤掉某些字节_python_Mangs-Python](https://devpress.csdn.net/python/6300a38e7e66823466196ace.html "在python中过滤掉某些字节_python_Mangs-Python")

相关推荐
开开心心就好6 小时前
仅168KB的桌面图标自动隐藏工具
windows·计算机视觉·计算机外设·excel·启发式算法·宽度优先·csdn开发云
蒋胜山12 小时前
Excel 练习题(7)
经验分享·excel
蒋胜山15 小时前
Excel 练习题(6)
经验分享·excel
wcy_101117 小时前
QCoder智能生成Excel数据清洗与可视化代码
python·excel
观无18 小时前
Python读取excel并形成api接口案例
python·pandas·fastapi
JoshRen1 天前
2026教程:上传Excel,用Gemini 3镜像站多模态一键生成问卷分析图表代码与结论(附国内免费方案)
excel
chushiyunen2 天前
pandas使用笔记、数据清洗、json_normalize
笔记·pandas
实战编程3 天前
Temu 插件导出 Excel 图片问题总结(SheetJS / ExcelJS)
excel
Data-Miner3 天前
用DeepSeek V4做表:数以轻舟Agent让做Excel表像聊天一样简单
microsoft·excel
Eiceblue3 天前
使用 C# 将 Excel 转换为 Markdown 表格(含批量转换示例)
开发语言·c#·excel