Python根据图片生成学生excel成绩表

学习笔记:

上完整代码

复制代码
import os
import re
from openpyxl import Workbook, load_workbook
from openpyxl.drawing.image import Image as ExcelImage
from PIL import Image as PilImage

# 定义图片路径和Excel文件路径
image_dir = './resources/stupics'  # 图片所在的文件夹路径,请根据实际情况修改
excel_path = './result/students_info.xlsx'  # Excel文件路径,请根据实际情况修改
output_folder = './result';
if not os.path.exists(output_folder):
    os.makedirs(output_folder)

# 定义图片名称格式的正则表达式
pattern = r'(?P<grade>\d{2})级(?P<major>[\u4e00-\u9fff]+)(?P<class>\d+班)(?P<name>[\u4e00-\u9fff]+)'

# 获取图片文件列表
image_files = [f for f in os.listdir(image_dir) if f.endswith(('.png', '.jpg', '.jpeg'))]

# 检查是否存在Excel文件,若不存在则创建新文件
if not os.path.exists(excel_path):
    wb = Workbook()
    ws = wb.active
    ws.title = "学生信息"
    # 写入表头
    headers = ["年级", "专业", "班级", "姓名", "照片"]
    ws.append(headers)
else:
    wb = load_workbook(excel_path)
    ws = wb.active

# 定义各列的固定宽度
column_widths = {
    'A': 10,  # 年级
    'B': 25,  # 专业
    'C': 8,   # 班级
    'D': 15,  # 姓名
    'E': 15   # 照片
}

# 应用固定列宽
for column, width in column_widths.items():
    ws.column_dimensions[column].width = width

# 遍历图片文件,解析名称并写入Excel
for image_file in image_files:
    match = re.match(pattern, os.path.splitext(image_file)[0])
    if match:
        info = match.groupdict()
        row = [
            info['grade'] + '级',
            info['major'],
            info['class'],
            info['name']
        ]
        ws.append(row)

        # 确保图片插入到正确的行
        img_path = os.path.join(image_dir, image_file)
        img = PilImage.open(img_path)
        excel_img = ExcelImage(img_path)
        excel_img.width, excel_img.height = 80, 110  # 根据需要调整图片大小

        # 计算图片宽度对应的字符数
        pixel_width = excel_img.width
        char_width = pixel_width / 7  # 假设每个字符约等于7个像素

        # 设置图片所在列的宽度
        cell_location = f'E{ws.max_row}'  # 使用当前最大行数作为图片插入位置
        ws.add_image(excel_img, cell_location)
        ws.column_dimensions['E'].width = char_width

        # 计算行高(假设每点约等于1.33像素)
        pixel_height = excel_img.height
        point_height = pixel_height / 1.33

        # 设置行高
        ws.row_dimensions[ws.max_row].height = point_height

# 保存工作簿
wb.save(excel_path)
print("数据已成功写入Excel文件")

这是结构

运行结果及其展示

免费,需要q

相关推荐
___波子 Pro Max.3 分钟前
Python环境配置:.pythonrc与PYTHONPATH详解
python
p***95003 分钟前
MySQL Workbench菜单汉化为中文
android·数据库·mysql
唐笑笑在哪5 分钟前
电机写代码时的注意事项
python
我的xiaodoujiao11 分钟前
使用 Python 语言 从 0 到 1 搭建完整 Web UI自动化测试学习系列 28--开源电商商城系统项目实战--封装注册页面
python·学习·测试工具·pytest
p***629911 分钟前
mysql--多表查询
数据库·mysql
天天找自己15 分钟前
TransNeXt 深度解析:聚合注意力机制的突破性视觉骨干网络
人工智能·pytorch·python·深度学习·神经网络
s***P98215 分钟前
MySQL远程连接错误解决:“Host is not allowed to connect to this MySQL server”详解
数据库·mysql
l***914719 分钟前
MySQL--》如何在MySQL中打造高效优化索引
android·mysql·adb
AI小云20 分钟前
【数据操作与可视化】Matplotlib绘图-基础功能
python·数据可视化
m***667328 分钟前
Python 爬虫实战案例 - 获取社交平台事件热度并进行影响分析
开发语言·爬虫·python