python提取excel中的表格并保存图片

直接上代码:

__author__ = 'yyzhang'

# 只能针对xlsx格式
import os
import time
from multiprocessing import Pool

import xlrd
from PIL import ImageGrab
import xlwings as xw

save_pic = r"D:\img"
os.makedirs(save_pic, exist_ok=True)


def excel_catch_screen1(shot_excel,sh_num):
    try:
        try:
            try:
                app = xw.App(visible=True, add_book=False)  # 使用xlwings的app启动

                wb = app.books.open(shot_excel)  # 打开文件
            except Exception as e:
                return 0
            try:
                sheet = wb.sheets[sh_num]  # 选定sheet
                all = sheet.used_range  # 获取有内容的range
                print(all.value)
                all.api.CopyPicture()  # 复制图片区域
                sheet.api.Paste()  # 粘贴
                img_name = (os.path.basename(shot_excel)).replace("xlsx", "png")
                pic = sheet.pictures[0]  # 当前图片
                print(type(pic))
                # print(pic)
                pic.api.Copy()  # 复制图片
                img = ImageGrab.grabclipboard()  # 获取剪贴板的图片数据
                print(type(img))
                pic_name=os.path.splitext(img_name)[0]+"_{}".format(i)+".png"
                # pic_name = img_name.replace("表格", "{}".format(sh_num))
                img.save(os.path.join(save_pic, pic_name))  # 保存图片
                pic.delete()  # 删除sheet上的图片

            except Exception as e:
                wb.close()  # 不保存,直接关闭
                app.quit()
                print(i)
                print(e)
                return 0
            wb.close()  # 不保存,直接关闭
            app.quit()
        except Exception as e:
            pass
            # wb.close()  # 不保存,直接关闭
            # app.quit()

    except Exception as e:
        print(e)
        wb.close()  # 不保存,直接关闭
        app.quit()


if __name__ == '__main__':
    pathnames = r"D:\excel"
    file_list=os.listdir(pathnames)
    file_list=[i for i in file_list if i.endswith("xlsx") and not i.startswith("~$")]
    for file in file_list:

        pathname=os.path.join(pathnames,file)
        print(pathname)
        # 获取到文件的sheet数
        try:
            b = xlrd.open_workbook(pathname)
        except Exception as e:
            continue
        print(b)
        shnum = len(b.sheets())
        for i in range(shnum):
            excel_catch_screen1(pathname, i)

  • 7
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

空弹壳

你的鼓励是我创作的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值