如何使用Python复制粘贴AutoCAD表格
我正在尝试使用pyautocad这个工具,从一个AutoCAD图纸中复制一个表格,然后把它粘贴到另一个图纸里。重要的是,我希望能保持表格的样式和位置不变。之后,脚本会填充这个表格。
我试过使用COPY和COPYBASE这两种方法(见下文),但我还是被要求手动选择对象和插入点。有没有人知道正确的做法是什么?
import os, time
import pyautocad
def copy_table(source_file, dest_file):
acad = pyautocad.Autocad(create_if_not_exists=True)
os.startfile(source_file)
time.sleep(5)
source_doc = acad.ActiveDocument
table = None
for obj in acad.iter_objects('AcDbTable'):
if obj.ObjectName == "AcDbTable":
table = obj
break
if not table:
print("Table not found in the source drawing.")
return
insertion_point = (1.15, 24.1162)
try:
acad.Application.SendCommand('ENTSEL\n')
acad.Application.SendCommand(f'{table.Handle}\n')
acad.Application.SendCommand(f'COPY\n')
# I've also tried this but still got prompted to select the table
source_doc.SendCommand(f"COPYBASE \n {table.Handle}\n {insertion_point[0]}\n {insertion_point[1]}\n")
print("table selected")
except Exception as e:
print(e)
os.startfile(dest_file)
time.sleep(5)
dest_doc = acad.ActiveDocument
# this part works
dest_doc.SendCommand('_PASTECLIP\n' + str(insertion_point[0] + 0) + ',' + str(insertion_point[1] + 0) + '\n')
1 个回答
0
我通过这个问题的评论找到了答案:如何使用pyautocad/comtypes在AutoCAD中从一个图纸复制对象到另一个图纸
下面是可以运行的代码:
import os, time
import pyautocad
def copy_table(source_file, dest_file):
acad = pyautocad.Autocad(create_if_not_exists=True)
os.startfile(source_file)
time.sleep(5)
source_doc = acad.ActiveDocument
table = None
for obj in acad.iter_objects('AcDbTable'):
if obj.ObjectName == "AcDbTable":
table = obj
break
if not table:
print("Table not found in the source drawing.")
return
handle_string = 'COPYBASE\n'
handle_string += '0,0,0\n'
handle_string += '(handent "' + table.Handle + '")\n'
handle_string += '\n'
try:
source_doc.SendCommand(handle_string)
print("table selected")
except Exception as e:
print(e)
os.startfile(dest_file)
time.sleep(5)
dest_doc = acad.ActiveDocument
# this part works
dest_doc.SendCommand('_PASTECLIP\n' + '0,0,0\n')
# Save changes and close documents
source_doc.Close()
dest_doc.Save()
dest_doc.Close()
print("Table copied successfully.")