高效Excel数据净化工具:一键清除不可见字符与格式残留

摘要

本文将分享一款基于Python的Excel数据净化工具,用于自动清除给定的Excel文档中指定工作表中的不可见字符、批注、单元格样式等冗余数据。脚本支持进度可视化展示,保留核心数据处理逻辑的同时确保文件格式规整,特别适用于需要规范数据格式的企业级应用场景。


架构流程图

异常处理 可视化组件 核心处理模块 存在 不存在 循环处理 完成所有行 输出错误信息 更新进度条 清理条件格式 清除不可见字符 移除批注 重置字体样式 清除填充颜色 用户输入 输入参数 加载Excel文件 工作表存在性检查 初始化清理 逐行处理单元格 保存新文件


工具脚本源码

python 复制代码
import openpyxl
from openpyxl.styles import NamedStyle, Font, Border
from openpyxl.formatting import Rule
import re
from tqdm import tqdm  # 新增进度条库
from openpyxl.styles import PatternFill

def clean_invisible_chars(text):
    """清除字符串中的不可见字符"""
    if not isinstance(text, str):
        return text
    # 清除控制字符(ASCII 0-31,除了\t\n\r)
    return re.sub(r'[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]', '', text)

def clear_all_and_save(input_file, output_file, sheet_name):
    """
    清除工作表中的:
    1. 不可见字符
    2. 批注
    3. 单元格样式
    """

    # 已清理的列表
    cleared_set = set()
    
    # 加载工作簿
    wb = openpyxl.load_workbook(input_file)
    # 创建无样式对象
    no_style = NamedStyle(name="Normal")
    # 创建无填充对象
    no_fill = PatternFill(fill_type=None)
    
    
    
    # 检查工作表是否存在
    if sheet_name not in wb.sheetnames:
        print(f"错误: 工作表 '{sheet_name}' 不存在。")
        print(f"可用工作表列表: {', '.join(wb.sheetnames)}")
        return
    
    # 获取工作表
    ws = wb[sheet_name]
    # 获取总行数用于进度条
    total_rows = ws.max_row
    
    
    
    first_init = True
    
    # 使用tqdm显示进度条
    for row in tqdm(ws.iter_rows(), total=total_rows, desc="处理进度"):

        if first_init == True:
            print(f"初始化完成,开始清理数据...")
            
            # 彻底清除所有条件格式和样式
            ws.conditional_formatting = []
            cleared_set.add('条件格式填充色')
            # cleared_set.add('单元格默认样式')
            print(f"✔ 已彻底清理 工作表:{sheet_name} 的所有样式设置, 开始单元格处理...")
                
            first_init = False
        
        for cell in row:
            # 彻底清除单元格所有样式
            cell.fill = PatternFill(fill_type=None)
            cell.font = Font(name='Calibri', size=11, bold=False, italic=False)
            cell.border = Border()
            cell.number_format = 'General'
            # 清除不可见字符
            if cell.value and isinstance(cell.value, str):
                cell.value = clean_invisible_chars(cell.value)
                cleared_set.add('不可见字符')
                
            # 清除批注
            if cell.comment:
                cell.comment = None
                cleared_set.add('批注')
                
            # 清除样式
            cell.style = no_style
            cleared_set.add('单元格样式')
            
            # 清除单元格填充颜色
            if cell.fill:
                cell.fill = no_fill
                cleared_set.add('单元格填充色')
    
    # 保存工作簿到新的文件
    wb.save(output_file)
    
    # cleared_text = ", ".join(cleared_set)
    cleared_text = "\n".join(f"  ✔ 清除-{item}" for item in cleared_set)
    # print(f"已清理[{cleared_text}],并保存到 {output_file}")
    print("已完成:\n"+cleared_text+f"\n并保存到 {output_file}")

# 使用示例
input_excel_file = r'测试-脱敏结果.xlsx'  # 输入Excel文件路径
output_excel_file = r'清除样式_测试-脱敏结果.xlsx'  # 输出Excel文件路径
sheet_to_clean = 'PB' # 'Sheet1'  # 要清理的工作表名称

print(f"初始化中...")
print(f"输入文件: {input_excel_file}")
print(f"输出文件: {output_excel_file}")
print(f"目标工作表: {sheet_to_clean}")
try:
    clear_all_and_save(input_excel_file, output_excel_file, sheet_to_clean)
except Exception as e:
    print(f"处理过程中发生错误: {str(e)}")

功能特性说明

1. 三重数据净化

  • 隐形字符清除:正则表达式过滤ASCII 0-31控制字符
  • 格式重置:统一字体、边框、填充样式为默认值
  • 元数据清理:移除单元格批注及条件格式

2. 可视化进度提示

采用tqdm库实现:

  • 实时处理进度条
  • 预估剩余时间
  • 已完成项目统计

3. 安全防护机制

  • 工作表存在性校验
  • 异常捕获与友好提示
  • 输出文件独立保存

典型应用场景

  1. 数据迁移前的格式标准化
  2. 第三方数据接入清洗
  3. 报表自动化生成预处理
  4. 敏感信息脱敏后处理
相关推荐
Zane199419 分钟前
create_task 和直接 await 到底有什么不一样?asyncio 的 Task、gather 与并发数量控制
后端·python
李可以量化21 分钟前
Redis 从了解到精通(四・下):分区技术原理与选型全解析
python
Python私教32 分钟前
创业团队做管理系统,别先堆页面:我把 14 个问题做成了需求门禁
后端·python·架构
云半S一40 分钟前
Python学习总结
python·学习·学习分享
苏子寒43 分钟前
Nano-VLLM全代码解析笔记(6)-embed_head和linear
pytorch·笔记·python·机器学习·ai·nlp·vllm
JTaoX1 小时前
PyCharm 连接本地虚拟机完整指南
ide·python·pycharm
Hi_Amos1 小时前
记一次 yfinance 源码调试:SOCKS5 代理下 Chart API 正常,历史数据却一直超时
python·k线·yfinance
青少儿编程课堂1 小时前
用图形化编程做一个“少年探险闯关”小游戏:方向键控制、碰撞检测与多关卡串起完整项目
c++·python·算法·bfs·信息学竞赛
evans在进步2 小时前
Spring Boot 工程化核心详解:Parent、Starter、热部署、事务与多数据源
spring boot·后端·python
战略性的菠萝2 小时前
学习笔记-Numpy知识
python·numpy