python实现Excel指定区域截图

发布时间 2023-12-04 13:34:13作者: cnblogs用户

方法一:xlwings

import os.path
import time
import uuid
from io import BytesIO
from typing import Union

import xlwings as xw
from PIL import ImageGrab


def excel_grab(excel_path, sheet_name: Union[str, int] = 0, cell_area=None, pic_path=None, visible=False, saved=True):
    """
    Excel指定区域截图
    :param excel_path: Excel文件路径
    :param sheet_name: 工作表名称或索引,0即第一张工作表
    :param cell_area: 截图区域,默认None,不指定时获取有内容的区域截图
    :param pic_path: 截图文件路径,png格式
    :param visible: 截图时是否打开显示Excel
    :param saved: 是否将截图保存到本地
    :return: png路径 或 图片的bytes
    """
    app = xw.App(visible=visible, add_book=False)
    wb = app.books.open(excel_path)
    if isinstance(sheet_name, str):
        sheet = wb.sheets(sheet_name)
    else:
        sheet = wb.sheets[sheet_name]
    if cell_area:
        pic_area = sheet[cell_area]
    else:
        pic_area = sheet.used_range  # 获取有内容的range
    try:
        pic_area.api.CopyPicture()  # 复制图片区域
        sheet.api.Paste()
        pic = sheet.pictures[0]  # 当前图片
        pic.api.Copy()
        time.sleep(.5)  # 等待copy完后再获取剪贴板的截图
        pic.delete()  # 删除sheet上的图片
    except Exception as e:
        print(e)
    finally:
        wb.close()
        app.quit()

    try:
        img = ImageGrab.grabclipboard()  # 获取剪贴板的图片数据
    except Exception as e:
        print(e)
        return '截图失败'
    if saved:
        if not pic_path:
            pic_path = f'{os.path.splitext(excel_path)[0]}_{uuid.uuid4().hex[:10]}.png'
        img.save(pic_path)
        return pic_path
    else:
        f = BytesIO()
        img.save(f, 'png')
        img_data = f.getvalue()
        f.close()
        return img_data