解决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")

相关推荐
wtsolutions28 分钟前
MCP Server Integration - JSON to Excel for AI and Automation
json·excel
开开心心就好2 小时前
音频编辑工具,多端支持基础剪辑易操作
java·网络·windows·java-ee·电脑·maven·excel
vfvfb5 小时前
excel多个合并 xlsx工作表合并 多个excel合并到一张表
excel
金融小白数据分析之路6 小时前
msoffcrypto-tool库 Excel 加密
python·excel
西红市杰出青年7 小时前
Python异步----------await方法逻辑
pandas
开开心心_Every10 小时前
文件数量统计工具:支持多层文件夹数量统计
游戏·微信·pdf·excel·语音识别·swift·lisp
私人珍藏库11 小时前
[吾爱大神原创工具] Excel 数据批量转 Word 工具(2026年最新版)
word·excel·工具·软件·win
linuxxx11011 小时前
excel365批量拆分列并填充单元格
excel
徐赛俊11 小时前
Excel 数据写入 PowerPoint 表格与文本框(涨跌幅颜色自动处理)
powerpoint·excel
好好学操作系统12 小时前
notion+excel自动创建表格| 了解了notion api
数据库·python·oracle·excel·notion