python实现excel保护

import openpyxl
from openpyxl.utils import get_column_letter
from openpyxl.styles import Protection
from openpyxl.worksheet.protection import SheetProtection


def protect_excel_sheet(input_file, output_file, password, protected_ranges=None, allow_select_locked_cells=True):
    """
    保护Excel工作表并设置密码

    参数:
    input_file (str): 输入Excel文件路径
    output_file (str): 输出Excel文件路径
    password (str): 保护密码
    protected_ranges (list): 要保护的单元格范围列表,例如 ['A1:C10', 'E1:E20']
    allow_select_locked_cells (bool): 是否允许选择锁定的单元格
    """
    try:
        # 加载工作簿
        wb = openpyxl.load_workbook(input_file)

        # 遍历所有表
        for sheet_name in wb.sheetnames:
            ws = wb[sheet_name]

            # 设置工作表保护
            ws.protection.sheet = True
            ws.protection.password = password

            # 设置默认保护属性
            ws.protection.autoFilter = True  # 允许使用自动筛选
            ws.protection.deleteColumns = True  # 允许删除列
            ws.protection.deleteRows = True  # 允许删除行
            ws.protection.formatCells = True  # 允许设置单元格格式
            ws.protection.formatColumns = True  # 允许设置列格式
            ws.protection.formatRows = True  # 允许设置行格式
            ws.protection.insertColumns = True  # 允许插入列
            ws.protection.insertHyperlinks = True  # 允许插入超链接
            ws.protection.insertRows = True  # 允许插入行
            ws.protection.pivotTables = True  # 允许使用数据透视表
            ws.protection.selectLockedCells = allow_select_locked_cells  # 允许选择锁定的单元格
            ws.protection.selectUnlockedCells = True  # 允许选择未锁定的单元格
            ws.protection.sort = True  # 允许排序

            # 如果指定了保护范围,则只锁定这些范围
            if protected_ranges:
                # 首先解锁所有单元格
                for row in ws.rows:
                    for cell in row:
                        cell.protection = Protection(locked=False)

                # 然后锁定指定范围
                for protected_range in protected_ranges:
                    min_col, min_row, max_col, max_row = openpyxl.utils.range_boundaries(protected_range)
                    for row in ws.iter_rows(min_row=min_row, max_row=max_row, min_col=min_col, max_col=max_col):
                        for cell in row:
                            cell.protection = Protection(locked=True)

            # 如果没有指定保护范围,则锁定整个工作表
            else:
                for row in ws.rows:
                    for cell in row:
                        cell.protection = Protection(locked=True)

        # 保存工作簿
        wb.save(output_file)
        print(f"工作表已成功保护并保存至 {output_file}")

    except Exception as e:
        print(f"处理Excel文件时出错: {e}")


# 使用示例
if __name__ == "__main__":
    input_file = "example.xlsx"  # 替换为你的输入文件路径
    output_file = "protected_example.xlsx"  # 替换为你的输出文件路径
    password = "123456"  # 替换为你要设置的密码

    # 可选:指定要保护的单元格范围
    protected_ranges = ["A1:C10", "E1:E20"]  # 示例范围,可根据需要修改

    # 调用函数保护工作表
    protect_excel_sheet(input_file, output_file, password, protected_ranges=None)    

你可能感兴趣的:(windows)