栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Python 读取某个目录下所有png图片导入Excel

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Python 读取某个目录下所有png图片导入Excel

一、安装xlsxwriter库 pip3 install xlsxwriter 二、代码
import xlsxwriter, os

image = []
# 打包前路径:os.path.abspath(__file__)
# 打包后路径:os.path.realpath(sys.executable))
# 获取文件目录下所有的.png图片
def GetImgPathFromFolder():
    for root, dirs, files in os.walk(os.path.dirname(os.path.abspath(__file__))):
        for file in files:
            if(os.path.join(root,file).endswith("png") ) :
                # 获取文件所属目录
                #print(root)
                # 获取文件所处的文件夹名
                #print(root.split(os.sep)[-1])
                # 获取文件名称
                #print(file)
                # 获取文件路径
                #print(os.path.join(root,file))
                image.append({'image_name': file, 'image_path': os.path.join(root, file)})

# 将所有图片导入Excel
def ImportImgToExcel():
    # 在同级目录新建表格
    workbook = xlsxwriter.Workbook('image.xlsx')
    worksheet = workbook.add_worksheet()
    # 设置文字格式
    property = {
        'font_size': 11,  # 字体大小
        'bold': True,  # 是否加粗
        'align': 'center',  # 水平对齐方式
        'valign': 'vcenter',  # 垂直对齐方式
        'font_name': u'微软雅黑',
        'text_wrap': True,  # 是否自动换行
    }
    cell_format = workbook.add_format(property)
    # 设置默认行高以及AB两例默认宽度,A1B1填入列名
    worksheet.set_default_row(75)
    worksheet.set_column("A:A", 13.75)
    worksheet.set_column("B:B", 13.75)
    worksheet.write("A1", "img_Name", cell_format)
    worksheet.write("B1", "img", cell_format)
    # 循环导入图片
    for i in range(len(image)):
        # A列添加图片名
        worksheet.write("A" + str(i + 2), image[i]['image_name'], cell_format)
        # B列添加图片,缩放0.1
        worksheet.insert_image('B' + str(i + 2), image[i]['image_path'], {'x_scale': 0.1, 'y_scale': 0.1})
    # 关闭文件
    workbook.close()

GetImgPathFromFolder()
ImportImgToExcel()
三、最终效果

​​​​​​​

 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/839968.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号