E-Documents & E-books

import xlwings as xw import os def copy_shapes_with_position(src_file, src_sheet_name, tgt_file, tgt_sheet_name): app = None try: # 检查文件是否存在 if not os.path.exists(src_file): raise FileNotFoundError(f"源文件不存在: {src_file}") if not os.path.exists(tgt_file): raise FileNotFoundError(f"目标文件不存在: {tgt_file}") print("启动 Excel 应用...") app = xw.App(visible=False) app.screen_updating = False # 打开工作簿 src_wb = app.books.open(src_file) tgt_wb = app.books.open(tgt_file) src_ws = src_wb.sheets[src_sheet_name] tgt_ws = tgt_wb.sheets[tgt_sheet_name] shapes = src_ws.shapes count = shapes.count print(f"在 '{src_sheet_name}' 中找到 {count} 个形状") if count == 0: print("警告:没有发现任何形状。") return for i, shape in enumerate(shapes): name = shape.name left = shape.left top = shape.top width = shape.width height = shape.height text = shape.text if hasattr(shape, 'text') and shape.text is not None else "" print(f"处理形状 {i+1}: {name} -> 位置({left}, {top}), 大小({width}x{height})") # 使用 .api 添加文本框(适用于文本类形状) try: # 在目标工作表中添加一个文本框 new_shape_api = tgt_ws.api.Shapes.AddTextbox( Orientation=1, # msoTextOrientationHorizontal Left=left, Top=top, Width=width, Height=height ) # 设置名称和文本 new_shape_api.Name = f"TextBox_Copied_{i + 1}" # 可选:保留原名或避免重复 new_shape_api.TextFrame.Characters().Text = text print(f"✅ 已添加文本框: {new_shape_api.Name}") except Exception as e: print(f"❌ 添加文本框失败 ({name}): {e}") # 保存目标文件 tgt_wb.save() print(f"✅ 成功保存到: {tgt_file}") except Exception as e: print(f"⛔ 发生错误: {e}") import traceback traceback.print_exc() finally: if app: print("关闭 Excel 应用...") app.quit() # 调用函数 copy_shapes_with_position( src_file='3104.xlsx', src_sheet_name='3104', tgt_file='test.xlsx', tgt_sheet_name='Sheet2' ) 会 发生错误: (-2147352567, '发生意外。', (0, None, None, None, 0, -2147467259), None)
11-26
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值