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标准的脱敏文档,适用于测试环境搭建、数据共享等隐私保护场景。
相关推荐
ZhengEnCi3 小时前
Excel 文件结构完全指南-从基础概念到 Python 读取的实用宝典
python·excel
核桃杏仁粉5 小时前
excel拼接数据库
数据库·oracle·excel
cx330上的猫5 小时前
价值1w的数据分析课知识点汇总-excel使用(第一篇)
数据挖掘·数据分析·excel
小薛引路9 小时前
office便捷办公06:根据相似度去掉excel中的重复行
windows·python·excel
CodeLongBear12 小时前
苍穹外卖 Day12 实战总结:Apache POI 实现 Excel 报表导出全流程解析
java·excel
技术钱21 小时前
vue3 封装图片上传预览组件支持docx、excel、pdf、图片、txt格式
vue.js·pdf·excel
r i c k1 天前
Excel表----VLOOKUP函数实现两表的姓名、身份证号码、银行卡号核对
excel
枫,为落叶1 天前
【vue】导出excel
前端·vue.js·excel
星空的资源小屋1 天前
RoboIntern,一款自动化办公小助手
运维·人工智能·pdf·自动化·电脑·excel
虎头金猫2 天前
我的远程开发革命:从环境配置噩梦到一键共享的蜕变
网络·python·网络协议·tcp/ip·beautifulsoup·负载均衡·pandas