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标准的脱敏文档,适用于测试环境搭建、数据共享等隐私保护场景。
相关推荐
海兰31 分钟前
【web应用】Excel 项目数据自动化分析系统(AI 驱动分析)详细设计与部署指南(附源代码)
前端·人工智能·自动化·excel
2501_930707788 小时前
使用 C# 代码读取或删除 Excel 文档属性
excel
hikktn9 小时前
Excel 日期格式统一治理:从“显示不全“到“自动兼容“的完整方案
windows·python·excel
霸道流氓气质11 小时前
Spring Boot 大数据量 Excel 导入导出功能实现指南
spring boot·后端·excel
霸道流氓气质11 小时前
Java 单元测试生成大量 Excel 测试数据实战指南
java·单元测试·excel
IT WorryFree12 小时前
FortiGate常用资产 OID 清单,配套 Excel 台账模板字段
网络·人工智能·excel
MyFreeIT12 小时前
Excel Enable Content
excel
E_ICEBLUE12 小时前
将 Excel 表格插入 Word 文档的三种实用方案(Python 自动化)
python·word·excel
俊哥工具12 小时前
027免费开源硬盘检测工具,一键查看健康度,杜绝数据丢失
pdf·电脑·word·excel·音视频
themingyi1 天前
Abaqus2024安装python包pandas
开发语言·python·pandas