
import os
import xlwings as xw
from PIL import ImageGrab
# ========= 自行修改这两个文件夹路径 =========
excel_dir = r"D:\Excel文件存放目录"
img_save_dir = r"D:\Excel截图保存目录"
# ===========================================
os.makedirs(img_save_dir, exist_ok=True)
def capture_excel(file_path, out_path):
try:
with xw.App(visible=True, add_book=False) as app:
wb = app.books.open(file_path)
ws = wb.sheets[0]
data_range = ws.used_range
range_addr = data_range.address
print(f"【{os.path.basename(file_path)}】识别区域:{range_addr}")
ws.range(range_addr).api.CopyPicture(Appearance=1, Format=2)
img = ImageGrab.grabclipboard()
if img:
img.save(out_path)
print(f"✅ 已保存:{out_path}\n")
else:
print(f"❌ 截图失败:剪贴板为空\n")
wb.close()
except Exception as err:
print(f"❌ 出错:{os.path.basename(file_path)} → {str(err)}\n")
if __name__ == "__main__":
total = 0
# 遍历目录下所有Excel文件
for file in os.listdir(excel_dir):
file_lower = file.lower()
if file_lower.endswith((".xlsx", ".xls")):
total += 1
excel_full_path = os.path.join(excel_dir, file)
# 提取文件名中的数字:f-1 → 1
file_name = os.path.splitext(file)[0]
num = file_name.split("-")[-1]
# 创建对应编号文件夹
sub_dir = os.path.join(img_save_dir, num)
os.makedirs(sub_dir, exist_ok=True)
# 图片统一命名为 f.png
save_path = os.path.join(sub_dir, "f.png")
capture_excel(excel_full_path, save_path)
print(f"批量处理完成,共处理 {total} 个文件")
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。