from PIL import ImageGrab # 需安装Pillow包
import xlwings as xw
import pandas as pd
import os
def main(*args, **kwargs):
"""
为文件夹下所有Excel工作簿的所有sheet截图
"""
exl_dir = kwargs.get('exl_dir')
for file_name in os.listdir(exl_dir):
if '.xlsx' in file_name:
file_path = os.path.join(exl_dir, file_name)
app = xw.App(visible=True, add_book=False)
wb = app.books.open(file_path)
sht_names = list(pd.read_excel(file_path, sheet_name=None))
for shot_sheetname in sht_names:
sheet = wb.sheets(shot_sheetname)
used_range = sheet.used_range
used_range.api.CopyPicture()
try: # 防止工作表有密码保护无法粘贴
sheet.api.Paste()
pic = sheet.pictures[0]
pic.api.Copy()
except:
xw.sheets.add(name='中转表', before=None, after=None)
sheet_new = wb.sheets('中转表')
sheet_new.api.Paste()
pic = sheet_new.pictures[0]
pic.api.Copy()
sheet_new.delete()
finally:
img = ImageGrab.grabclipboard()
img_path = os.path.join(r'D:\桌面\截图', file_name + '-' + shot_sheetname + '.png')
img.save(img_path)
wb.close()
app.quit()
if __name__ == '__main__':
main(exl_dir=r'D:\桌面')
Python为文件夹下所有Excel工作簿的所有sheet截图
于 2022-10-27 11:12:57 首次发布