python 图片插入excel

python 复制代码
from openpyxl import Workbook, load_workbook
from openpyxl.drawing.image import Image
from openpyxl.drawing.spreadsheet_drawing import AnchorMarker, TwoCellAnchor
import numpy as np
import os
from openpyxl.styles import Alignment

def GetImgNameByEveryDir(file_dir,videoProperty):
    FileNameWithPath = []
    FileName = []
    FileDir = []
    for root, dirs, files in os.walk(file_dir):
        for file in files:
            if os.path.splitext(file)[1] in videoProperty:
                FileNameWithPath.append(os.path.join(root, file))  # 保存图片路径
                FileName.append(file)                              # 保存图片名称
                FileDir.append(root + '/')            # 保存图片所在文件夹
    return np.array(FileName), np.array(FileNameWithPath),FileDir

## 循环便利文件
class Generate(object):
    def __init__(self,xls_save_path,file_dir=None):
        self.file_name = xls_save_path
        self.file_dir  = file_dir
        pass
    def save_one_dir_imgs_to_excel(self):
        if os.path.exists(self.file_name)==False:
            wb = Workbook()# 使用openpyxl创建新的workbook
        else:
            wb = load_workbook(filename=self.file_name)

        try:
            ws = wb['Sheet']
            wb.remove(ws)  # 删掉默认的sheet
        except:
            print('默认sheet不存在,不用删除...')
        ws = wb.active
        ff,pp,dd = GetImgNameByEveryDir(self.file_dir,['.jpg'])
        ws = wb.create_sheet('仪表结果')# 根据文件夹名称创建sheet
        alignment_center = Alignment(horizontal='center', vertical='center')
        ws.cell(row=1, column=1, value='结果图片').alignment = alignment_center# 设置第一行的字段
        ws.cell(row=1, column=2, value='图片名称').alignment = alignment_center
        ws.cell(row=1, column=3, value='仪表读数').alignment = alignment_center
        ws.cell(row=1, column=4, value='错误类型').alignment = alignment_center
        
        for kk in range(len(pp)):
            ws.row_dimensions[kk+2].height   = 150
            ws.column_dimensions["A"].width  = 30
            ws.column_dimensions["B"].width  = 60
            ws.column_dimensions["C"].width  = 10
            ws.column_dimensions["D"].width  = 10
            ws.cell(row=kk+2, column=3, value='222222').alignment = alignment_center   # 后面的.alignment是单元格内容居中
            ws.cell(row=kk+2, column=2, value=pp[kk]).alignment   = alignment_center


            img   = Image(pp[kk])# 创建openpyxl的Image对象
            _from = AnchorMarker(0, 50000, kk+1, 50000)# 创建锚标记对象,设置图片所占的row
            to    = AnchorMarker(1, -50000, kk+1+1, -50000)# 创建锚标记对象,设置图片所占的row 从而确认了图片位置
            img.anchor = TwoCellAnchor('twoCell', _from, to)# 将锚标记对象设置图片对象的锚属性,图形就具备了所在位置
            ws.add_image(img)# 添加图片
            


        # print(allfiles)
        wb.save(self.file_name)

    def save_one_result_to_excel(self,resultImgPath,resultMeter,meterErrorType,dir1,dir2):
        if os.path.exists(self.file_name)==False:
            wb = Workbook()# 使用openpyxl创建新的workbook
        else:
            wb = load_workbook(filename=self.file_name)

        try:
            ws = wb['Sheet']
            wb.remove(ws)  # 删掉默认的sheet
        except:
            print('默认sheet不存在,不用删除...')

        sheet_names      = wb.sheetnames
        print('ws sheet  = ',sheet_names)
        ws               = wb.active
        if '仪表结果' not in sheet_names:
            ws           = wb.create_sheet('仪表结果')# 根据文件夹名称创建sheet
        alignment_center = Alignment(horizontal='center', vertical='center')
        rows             = ws.max_row
        columns          = ws.max_column
        resultImgPath2   = resultImgPath.replace('\\', '/')
        imgName          = resultImgPath2.split('/')[-1] # linux用这个

        print('rows = ',rows)
        ws.cell(row = 1, column = 1, value = '结果图片').alignment = alignment_center# 设置第一行的字段
        ws.cell(row = 1, column = 2, value = '图片名称').alignment = alignment_center
        ws.cell(row = 1, column = 3, value = '仪表读数').alignment = alignment_center
        ws.cell(row = 1, column = 4, value = '错误类型').alignment = alignment_center
        
        ws.row_dimensions[rows+1].height = 150
        ws.column_dimensions["A"].width  = 30
        ws.column_dimensions["B"].width  = 10
        ws.column_dimensions["C"].width  = 30
        ws.column_dimensions["D"].width  = 10
        # ws.cell(row = rows + 1, column = 3, value = resultMeter).alignment    = alignment_center   # 后面的.alignment是单元格内容居中
        ws.cell(row = rows + 1, column = 2, value = '').alignment        = alignment_center
        # ws.cell(row = rows + 1, column = 4, value = meterErrorType).alignment = alignment_center
        # ws.cell(row = rows + 1, column = 5, value = meterErrorType).alignment = alignment_center

        try:
            resultImgPath1 = dir1 + '/' + imgName
            img        = Image(resultImgPath1)# 创建openpyxl的Image对象
            _from      = AnchorMarker(0,  50000, rows+0,  50000)# 创建锚标记对象,设置图片所占的row
            to         = AnchorMarker(1, -50000, rows+1, -50000)# 创建锚标记对象,设置图片所占的row 从而确认了图片位置
            img.anchor = TwoCellAnchor('twoCell', _from, to)# 将锚标记对象设置图片对象的锚属性,图形就具备了所在位置
            ws.add_image(img)# 添加图片

            resultImgPath2 = dir2 + '/' + imgName
            img2        = Image(resultImgPath2)# 创建openpyxl的Image对象
            _from2      = AnchorMarker(2,  50000, rows+0,  50000)# 创建锚标记对象,设置图片所占的row
            to2         = AnchorMarker(3, -50000, rows+1, -50000)# 创建锚标记对象,设置图片所占的row 从而确认了图片位置
            img2.anchor = TwoCellAnchor('twoCell', _from2, to2)# 将锚标记对象设置图片对象的锚属性,图形就具备了所在位置
            ws.add_image(img2)# 添加图片
        except:
            print('')


        
        wb.save(self.file_name)

def GetImgNameByEveryDir(file_dir,videoProperty):
    FileNameWithPath = []
    FileName = []
    FileDir = []
    for root, dirs, files in os.walk(file_dir):
        for file in files:
            if os.path.splitext(file)[1] in videoProperty:
                FileNameWithPath.append(os.path.join(root, file))  # 保存图片路径
                FileName.append(file)                              # 保存图片名称
                FileDir.append(root + '/')            # 保存图片所在文件夹
    return np.array(FileName), np.array(FileNameWithPath),FileDir

dir_need1 = '图1文件夹/'       # 原图文件夹
dir_need2 = '图2文件夹/'   # 结果图文件夹
ge=Generate('保存图片到excel.xlsx',dir_need1)
ff,pp,dd = GetImgNameByEveryDir(dir_need1,['.jpg'])
for k in range(len(ff)):
    ge.save_one_result_to_excel(pp[k],'1234','1235',dir_need1,dir_need2)

插入展示如下:

相关推荐
翔云API3 分钟前
PHP静默活体识别API接口应用场景与集成方案
人工智能
浊酒南街9 分钟前
吴恩达深度学习笔记:卷积神经网络(Foundations of Convolutional Neural Networks)4.9-4.10
人工智能·深度学习·神经网络·cnn
Tony聊跨境25 分钟前
独立站SEO类型及优化:来检查这些方面你有没有落下
网络·人工智能·tcp/ip·ip
懒惰才能让科技进步31 分钟前
从零学习大模型(十二)-----基于梯度的重要性剪枝(Gradient-based Pruning)
人工智能·深度学习·学习·算法·chatgpt·transformer·剪枝
yyfhq39 分钟前
sdnet
python
Qspace丨轻空间42 分钟前
气膜场馆:推动体育文化旅游创新发展的关键力量—轻空间
大数据·人工智能·安全·生活·娱乐
没有不重的名么43 分钟前
门控循环单元GRU
人工智能·深度学习·gru
测试19981 小时前
2024软件测试面试热点问题
自动化测试·软件测试·python·测试工具·面试·职场和发展·压力测试
love_and_hope1 小时前
Pytorch学习--神经网络--搭建小实战(手撕CIFAR 10 model structure)和 Sequential 的使用
人工智能·pytorch·python·深度学习·学习
2403_875736871 小时前
道品科技智慧农业中的自动气象检测站
网络·人工智能·智慧城市