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标准的脱敏文档,适用于测试环境搭建、数据共享等隐私保护场景。
相关推荐
倔强的小石头_15 小时前
Python 从入门到实战(十):Pandas 数据处理(高效搞定表格数据的 “瑞士军刀”)
人工智能·python·pandas
梦幻通灵20 小时前
Excel序列生成的4种方案实战
excel
万粉变现经纪人1 天前
Python系列Bug修复PyCharm控制台pip install报错:如何解决 pip install 网络报错 企业网关拦截 User-Agent 问题
网络·python·pycharm·beautifulsoup·bug·pandas·pip
Lucky高1 天前
Pandas库实践1_预备知识准备
python·pandas
墨上烟雨2 天前
Pandas 数据结构 - Series
数据结构·pandas
2501_930707782 天前
使用C#代码将 Excel 转换为 ODS,或将 ODS 转换为 Excel
excel
缺点内向2 天前
如何在 C# .NET 中将 Markdown 转换为 PDF 和 Excel:完整指南
pdf·c#·.net·excel
m5655bj2 天前
如何通过 Python 在 Excel 中添加或删除图片
python·excel
伍一512 天前
芋道框架下的进销存升级(三):Yudao-ERP2异步导出/导入Excel的设计与实现
java·excel·异步导出excel
CodeCraft Studio2 天前
Excel处理控件Aspose.Cells教程:使用C#在Excel中创建旭日图
c#·excel·aspose·excel旭日图·excel库·excel开发控件·excel api库