Python使用Win32com實現 Excel多個Sheet截圖
參考原文: python 对excel进行截图
1 from win32com.client import Dispatch, DispatchEx 2 import pythoncom 3 from PIL import ImageGrab, Image 4 import uuid 5 6 7 # screen_area——类似格式"A1:J10" 8 def excel_catch_screen(filename, sheetname, screen_area, img_name=False): 9 """ 对excel的表格区域进行截图——用例:excel_catch_screen(ur"D:\Desktop\123.xlsx", "Sheet1", "A1:J10")""" 10 pythoncom.CoInitialize() # excel多线程相关 11 12 excel = DispatchEx("Excel.Application") # 启动excel 13 excel.Visible = False # 可视化 14 excel.DisplayAlerts = False # 是否显示警告 15 wb = excel.Workbooks.Open(filename) # 打开excel 16 wb.Sheets(sheetname).select # 視圖切換到sheetname表 17 ws = wb.Sheets(sheetname) # 选择sheet 18 19 ws.Range(screen_area).CopyPicture() # 复制图片区域 20 ws.Paste() # 粘贴 ws.Paste(ws.Range('B1')) # 将图片移动到具体位置 21 22 name = str(uuid.uuid4()) # 重命名唯一值 23 new_shape_name = name[:6] 24 excel.Selection.ShapeRange.Name = new_shape_name # 将刚刚选择的Shape重命名,避免与已有图片混淆 25 26 ws.Shapes(new_shape_name).Copy() # 选择图片 27 img = ImageGrab.grabclipboard() # 获取剪贴板的图片数据 28 if not img_name: 29 img_name = name + ".PNG" 30 img.save(img_name) # 保存图片 31 wb.Close(SaveChanges=0) # 关闭工作薄,不保存 32 excel.Quit() # 退出excel 33 pythoncom.CoUninitialize() 34 35 36 if __name__ == '__main__': 37 pass 38 # excel_catch_screen(ur"D:\Desktop\123.xlsx", "Sheet1", "A1:J10")若要在多個Sheet中截圖
使用 wb.Sheets(sheetname).select 切換 Sheet 再截圖