Tuesday, October 17, 2023

Python + AutoCAD, Extract to Excel

 

Here’s a sample extracting attributes from multiple drawings. I use ObjectDBX to open each drawing and collect the attributes from a block named ‘elev’, a block that holds room numbers etc., Openpyxl makes it incredibly easy to write to and excel file. I think the question, “How do I write to excel” is one of the most frequently ask in the CAD forums. In python it’s a breeze  

import PyRx as Rx
import PyGe as Ge
import PyGi as Gi
import PyDb as Db
import PyAp as Ap
import PyEd as Ed
import traceback

import AxApp24 as Ax
import AxAppUtils24 as AxUt

import openpyxl as Ex  # using openpyxl

def PyRxCmd_dbxextract():
    try:
        paths = ["e:\\06457Submittal.dwg",
                 "e:\\06457Submittal2.dwg",
                 "e:\\06457Submittal3.dwg"]

        wb = Ex.Workbook()
        ws = wb.active
       
        nrow = 1
        axDoc = Ax.getDbx()
        for dwg in paths:
            axDoc.Open(dwg, None)
            for ent in axDoc.ModelSpace:
                if ent.EntityName != 'AcDbBlockReference':
                    continue
                #cast
                ref = Ax.IAcadBlockReference(ent)
                if ref.Name != 'elev':
                    continue
                nrow += 1
                for ncol, att in enumerate(ref.GetAttributes()):
                    ws.cell(row=nrow, column=ncol+1, value=att.TextString)

        wb.save('e://ItsAlive2.xlsx')
    except Exception as err:
        traceback.print_exception(err)

 


No comments:

Post a Comment

TraceBoundary sample in Python for AutoCAD

    import traceback from pyrx_imp import Rx from pyrx_imp import Ge from pyrx_imp import Gi from pyrx_imp import Db from pyrx_imp...