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

相关推荐
moz与京3 小时前
[附C++,JS,Python题解] Leetcode 面试150题(10)——轮转数组
c++·python·leetcode
影子24014 小时前
Navicat导出mysql数据库表结构说明到excel、word,单表导出方式记录
数据库·mysql·excel
什码情况4 小时前
回文时间 - 携程机试真题题解
数据结构·python·算法·华为od·机试
Alfadi联盟 萧瑶5 小时前
Python-Django入手
开发语言·python·django
漠北尘-Gavin6 小时前
【Python3.12.9安装llama-cpp-python遇到编译报错问题解决】
python·llama
测试老哥6 小时前
什么是集成测试?集成的方法有哪些?
自动化测试·软件测试·python·测试工具·职场和发展·单元测试·集成测试
豆芽8197 小时前
Conda配置Python环境
python·conda·pip
CANI_PLUS7 小时前
python 列表-元组-集合-字典
开发语言·python
东方佑7 小时前
使用 Python 自动处理 Excel 数据缺失值的完整指南
开发语言·python·excel