Excel数据脱敏利器:自动保留格式的智能脱敏脚本

源码:

python 复制代码
import openpyxl
import re
import random
import string
from openpyxl.utils import get_column_letter
from copy import copy
from tqdm import tqdm

def mask_data(value):
    """脱敏处理数据"""
    if isinstance(value, str):
        if value.strip() == "":
            return value
        # 保留数字格式
        if re.match(r'^\d+$', value):
            return ''.join(random.choice('0123456789') for _ in value)
        # 保留字母格式
        elif re.match(r'^[a-zA-Z]+$', value):
            return ''.join(random.choice(string.ascii_letters) for _ in value)
        else:
            return ''.join(random.choice(string.ascii_letters + string.digits) for _ in value)
    elif isinstance(value, (int, float)):
        return random.randint(0, 999999)
    return value

def mask_sheet_name(name):
    """脱敏处理sheet名称"""
    if len(name) == 0:
        return "Sheet_" + ''.join(random.choice(string.ascii_uppercase) for _ in range(3))
    return ''.join(random.choice(string.ascii_uppercase) for _ in name)

def mask_excel_file(input_path, output_path):
    """主函数:处理Excel文件"""
    # 加载工作簿
    wb = openpyxl.load_workbook(input_path)
    
    # 创建新工作簿
    new_wb = openpyxl.Workbook()
    new_wb.remove(new_wb.active)  # 移除默认创建的sheet
    
    # 处理每个工作表
    for sheet in tqdm(wb.worksheets, desc="处理工作表中", unit="sheet"):
        # 创建新sheet并重命名
        new_sheet = new_wb.create_sheet(title=mask_sheet_name(sheet.title))
        
        # 复制样式和数据
        for row in tqdm(sheet.iter_rows(), desc=f"处理{sheet.title}的行", unit="row", leave=False):
            for cell in row:
                if cell.__class__.__name__ == 'MergedCell':
                    continue
                new_cell = new_sheet.cell(row=cell.row, column=cell.column, value=mask_data(cell.value))
                if cell.has_style:
                    new_cell.font = copy(cell.font)
                    new_cell.border = copy(cell.border)
                    new_cell.fill = copy(cell.fill)
                    new_cell.number_format = cell.number_format
                    new_cell.protection = copy(cell.protection)
                    new_cell.alignment = copy(cell.alignment)
        
        # 复制列宽
        for col in sheet.columns:
            new_sheet.column_dimensions[get_column_letter(col[0].column)].width = \
                sheet.column_dimensions[get_column_letter(col[0].column)].width
    
    # 保存新工作簿
    new_wb.save(output_path)
    print(f"脱敏完成,结果已保存到: {output_path}")

if __name__ == "__main__":
    # 直接设置输入输出文件路径
    input_file = r"待脱敏数据.xlsx"  # 修改为您需要的输入文件路径
    output_file = "测试-脱敏结果.xlsx"  # 修改为您需要的输出文件路径
    
    mask_excel_file(input_file, output_file)

📝 备注:

该数据脱敏脚本采用openpyxl库实现Excel文件的全自动化处理,具备三大特色能力:

  1. 智能数据识别 - 根据内容类型(纯数字/字母/混合)生成格式匹配的随机值,如"13812345678"转为"59175032816"
  2. 格式无损保留 - 完美继承原文件样式(字体/边框/对齐方式/数值格式)和列宽配置
  3. 深度脱敏机制 - 同步处理工作表名称,自动生成随机sheet名(如"Report"转为"XKQ")
  4. 可视化进度 - 通过tqdm进度条直观展示每个sheet和每行数据的处理进度
    工具支持批量处理.xlsx文件,仅需指定输入输出路径即可生成符合GDPR标准的脱敏文档,适用于测试环境搭建、数据共享等隐私保护场景。
相关推荐
疯狂小猫咪5 小时前
中小培训机构教务数字化踩坑复盘|从 Excel 过渡到教务系统经验总结
小程序·excel
开开心心_Every12 小时前
实现鼠标键盘动作录制与重复播放的工具
微信·jupyter·pycharm·pdf·计算机外设·word·excel
智途 Tech16 小时前
2026年分析多个Excel、CSV和网页数据的AI工具清单:Tabbit 浏览器多源引用
大数据·人工智能·excel
ltqvibe18 小时前
AI问数、找IT取数、自己导Excel,三条路怎么选
人工智能·excel·数据报表·智能问数·ai问数·本体语义·取数
ISBN图书20 小时前
ISBN 批量查询怎么做?用 Excel 一次补全书名、作者和出版社信息
excel·isbn·图书数据
Irene199120 小时前
获取 Excel 填充色的十六进制颜色值:取色器 + 手动转 RGB
excel·wps
三十岁老牛再出发21 小时前
8月27日总结
python·pandas
砚底藏山河21 小时前
【量化纯GET实战 #21】用 pandas 做分析:把接口数据变成 DataFrame
java·python·金融·maven·pandas
E_ICEBLUE1 天前
为 Excel 工作簿和工作表设置密码保护【Python教程】
python·excel
小白学大数据2 天前
超简单:用 Python 让 Excel 飞起来:用 openpyxl 把重复报表整理交给脚本
开发语言·数据库·python·excel