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标准的脱敏文档,适用于测试环境搭建、数据共享等隐私保护场景。
相关推荐
CircleMouse2 小时前
如何设置wps单元格下拉选项设置
excel·wps
zhangjin12227 小时前
kettle插件-excel插件,kettle读取excel动态表头,kettle根据列名读取excel
excel·kettle·kettle excel插件·kettle 动态excel
远洪1 天前
excel 找出两列不同的数据
excel
pcplayer1 天前
非常好用的 Excel 读写控件
excel·delphi·office
Navicat中国1 天前
使用 Navicat 导入向导导入 Excel 数据时,系统提示导入成功,表中也能看到数据,但行数统计显示为 0,这是什么原因?
数据库·excel·导入
穿着内裤的外星人1 天前
触控精灵远程读写Excel步骤配置
excel
是孑然呀1 天前
【小记】excel vlookup一对多(第二篇)
excel
开开心心就好1 天前
专为视障人士设计的免费辅助工具
windows·计算机视觉·计算机外设·excel·散列表·推荐算法·csdn开发云
transformer_WSZ1 天前
excel两列数据绘制折线图
excel·折线图
蒋胜山2 天前
Excel 练习题(5)
经验分享·excel