首页 > 其他分享 >openpyxl 操作 execl 示例

openpyxl 操作 execl 示例

时间:2024-05-24 10:41:49浏览次数:15  
标签:execl sheet openpyxl 示例 column cell length new password

代码功能

对execl 的主机生成唯一不重复的密码。

代码示例

import secrets
import string
from datetime import datetime
from openpyxl import load_workbook
from openpyxl.utils import get_column_letter
from openpyxl.styles import Border, Side, Alignment


def create_password(password_length, minimum_digits):
    """
    生成符合安全要求的密码。
    """
    characters = string.ascii_letters + string.digits + string.punctuation
    while True:
        password = ''.join(secrets.choice(characters) for _ in range(password_length))
        if sum(c.isdigit() for c in password) >= minimum_digits:
            return password

def get_unique_password(existing_passwords, password_length, minimum_digits):
    while True:
        unique_password = create_password(password_length, minimum_digits)
        if unique_password not in existing_passwords:
            existing_passwords.add(unique_password)
            return unique_password
        
def update_excel_passwords(file_path, start_row, column_index, password_length, minimum_digits):
    """
    更新Excel文件中的密码,并设置样式。
    """
    try:
        book = load_workbook(file_path)
        sheet = book.active

        existing_passwords = set()
        
        date_str = datetime.now().strftime("%Y-%m-%d-%H-%M-%S")
        new_sheet = book.create_sheet(title=date_str, index=0)

        # 单元格格式设置
        thin_border = Side(style='thin')
        center_alignment = Alignment(horizontal='center', vertical='center')
        left_alignment = Alignment(horizontal='left', vertical='top')

        # 设置单元格边框和对齐方式
        for i, row in enumerate(sheet.iter_rows(), start=1):
            for j, cell in enumerate(row, start=1):
                new_cell = new_sheet.cell(row=i, column=j, value=cell.value)
                new_cell.border = Border(left=thin_border, right=thin_border, top=thin_border, bottom=thin_border)
                new_cell.alignment = center_alignment if i == 1 else left_alignment

        # 更新密码
        for i in range(start_row, new_sheet.max_row + 1):
            unique_password = get_unique_password(existing_passwords, password_length, minimum_digits)
            cell = new_sheet.cell(row=i, column=column_index)
            cell.value = unique_password

        # 计算并设置每列的最大宽度
        for col in range(1, new_sheet.max_column + 1):
            column_letter = get_column_letter(col)
            max_lengths = [len(str(cell.value)) for cell in new_sheet[column_letter]]
            max_length = max(max_lengths) if max_lengths else 0
            new_sheet.column_dimensions[column_letter].width = (max_length + 2) * 1.2

        book.save(file_path)
        book.close()

    except Exception as e:
        print(f"发生错误: {e}")


if __name__ == '__main__':
   # Excel 文件路径
    file_path = r'F:\work\python\files\password.xlsx'
    # 密码所在列的索引
    column_index = 2
    # 密码长度
    password_length = 16
    # 密码中至少包含的数字个数
    minimum_digits = 3
    # 从第二行开始更新,保留标题行
    start_row = 2

    # 更新 Excel 中指定列的密码,自动调整列宽并为每个单元格添加边框和对齐样式
    update_excel_passwords(file_path, start_row, column_index, password_length, minimum_digits)

标签:execl,sheet,openpyxl,示例,column,cell,length,new,password
From: https://www.cnblogs.com/wangguishe/p/18196330

相关文章

  • openpyxl 读取 execl
    按列读取数据fromopenpyxlimportWorkbook#创建一个新的Excel工作簿wb=Workbook()#获取第一个工作表worksheet=wb.active#多行数据data=[['Bob',25,'Male'],['Charlie',35,'Male'],['Alice',30,'Engin......
  • 百度智能云,流式请求示例
    前端<!DOCTYPEhtml><htmllang="en"><head><metacharset="UTF-8"><title>Sample</title></head><body><labelfor="textInput">Prompt:</label><inputtype......
  • 人脸识别库 虹软 客户端 服务端 示例
    https://github.com/18628271760/MultipleFacesProcess 一、前言虹软开发SDK以来,其免费使用的营销策略,成功降低了中小企业使用人脸识别技术的成本。然而,对.NET开发者来说,虹软没有提供C#版本的SDK供开发者直接调用(为什么JAVA就有?!),而是建议开发者利用C++版本封装。大龄的C系程......
  • openpyxl utils 模块
    utils模块说明openpyxl.utils模块提供了一些有用的工具来处理Excel表格中的行号和列号的转换。column_index_from_string()column_index_from_string():用于将Excel列字母转换为列索引。column_index_from_string(col_str):col_str(str):列字母字符串,例如'A','......
  • qt之点的绘制示例demo
    #include"mainwindow.h"#include"ui_mainwindow.h"#include<QPainter>#include<QColor>QColorm_color;intm_x=0;intm_y=0;intm_w=0;intm_h=0;MainWindow::MainWindow(QWidget*parent):QMainWindow(parent)......
  • tensorflow.js示例笔记 - predict-download-time
    预测下载时间。<!DOCTYPEhtml><html><head><title>predict-download-time</title><style>canvas{border:1pxsolid#d3d3d3;}</style><sc......
  • tensorflow.js示例笔记 - mnist
    使用层来进行数字识别,使用tf.layersapi训练模型识别MNIST数据库中的手写数字。index.html<html><head><title>MNIST</title><metacharset="UTF-8"><metaname="viewport"content="width=device-width,......
  • tensorflow.js示例笔记 - boston-housing
    多元回归,比较不同的房价预测模型。index.html<htmllang="en"><head><metacharset="UTF-8"><metaname="viewport"content="width=device-width,initial-scale=1"><title>Mult......
  • tensorflow.js示例笔记 - iris
    根据鸢尾花的数据对花进行分类,使用神经网络对结构化(表格)数据进行分类。index.html<html><head><metacharset="UTF-8"><metaname="viewport"content="width=device-width,initial-scale=1"><linkrel="......
  • C#连接Access数据库 查询和新增 示例
    C#连接Access数据库查询和新增示例项目中需要做一个写程序操作日志的需求,仅本机使用。这时Access数据库就是一个非常好的选择,简单,好用。下面仅仅是一个示例,简单写出查询和新增等C#操作Access数据库的代码效果图 clsDBHelperAccess.csusingSystem;usingSystem......