直接上代码:
__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)