Search This Blog

How to Automatically Export Closed Polyline Centroids & Areas from AutoCAD to CSV

🚀 AutoCAD Productivity Hack: Automate Centroid Extraction & Area Reports to CSV! 📐📊
If you’ve ever had to manually extract the coordinates and areas of dozens of closed polygons in AutoCAD for a surveying, GIS, or quantity takeoff project, you know how tedious it can be.
To save hours of clicking, I put together a custom AutoLISP routine that fully automates the process.
What it does in exactly 3 clicks:
1️⃣ Filters and selects only closed polylines (no accidental clicks on lines/text).
2️⃣ Calculates the exact mathematical center of mass (true centroid)—even for complex, irregular, or concave shapes!
3️⃣ Automatically places a CAD point and a physical text label showing the Area right inside your drawing.
4️⃣ Exports everything into a perfectly formatted CSV file (ID, Layer, Area, X, Y) ready for Excel or Google Sheets.
No manual data entry. Zero typos. Massive time savings.

📋 The AutoLISP Source Code:

lisp




    you can write your code between this  (vl-load-com)

(defun c:ExportCentroids ( / ss i ent obj layerName polyArea center csvPath fileHandle ptX ptY region pt3D textObj txtHeight areaStr)
  (princ "\nSelect closed polylines to export centroids and place Area labels...")
  
  ;; Set text height for the labels (adjust this number based on your drawing scale)
  (setq txtHeight (getvar "TEXTSIZE")) 
  
  ;; 1. Prompt user to select closed polylines
  (if (setq ss (ssget '((0 . "*POLYLINE") (-4 . "&=") (70 . 1))))
    (progn
      ;; 2. Prompt user for where to save the CSV file
      (setq csvPath (getfiled "Save Polyline Data As" "" "csv" 1))
      
      (if csvPath
        (progn
          ;; 3. Open the file for writing
          (setq fileHandle (open csvPath "w"))
          
          ;; Write CSV Headers
          (write-line "ID,Layer,Area,X_Coordinate,Y_Coordinate" fileHandle)
          
          (setq i 0)
          ;; 4. Loop through each selected polyline
          (while (< i (sslength ss))
            (setq ent (ssname ss i))
            (setq obj (vlax-ename->vla-object ent))
            
            ;; Extract Layer Name and Area
            (setq layerName (vlax-get obj 'Layer))
            (setq polyArea (vlax-get obj 'Area))
            
            ;; Convert Area value to a formatted string (2 = Decimal, 4 = Decimal Places)
            (setq areaStr (rtos polyArea 2 4))
            
            ;; Convert polyline temporarily to a region to get the true geometric centroid
            (setq region (vlax-invoke (vla-get-modelspace (vla-get-activedocument (vlax-get-acad-object))) 'AddRegion (list obj)))
            
            (if region
              (progn
                ;; Get centroid list (X Y) from temporary region
                (setq center (vlax-get (car region) 'Centroid))
                (setq ptX (car center))
                (setq ptY (cadr center))
                
                ;; Format a 3D point variant needed for placing CAD elements (Z set to 0.0)
                (setq pt3D (vlax-3d-point (list ptX ptY 0.0)))
                
                ;; --- DRAWING LABELS ---
                ;; A. Add a CAD Point at the exact centroid
                (vla-addpoint (vla-get-modelspace (vla-get-activedocument (vlax-get-acad-object))) pt3D)
                
                ;; B. Add a Text Label showing the Area string, slightly offset so it doesn't overlap the point
                (setq textObj (vla-addtext 
                                (vla-get-modelspace (vla-get-activedocument (vlax-get-acad-object))) 
                                areaStr 
                                (vlax-3d-point (list (+ ptX (/ txtHeight 2)) (+ ptY (/ txtHeight 2)) 0.0)) 
                                txtHeight
                              ))
                ;; Match the text layer to the polyline layer
                (vlax-put textObj 'Layer layerName)
                
                ;; Write data row to CSV
                (write-line 
                  (strcat 
                    (itoa (+ i 1)) "," 
                    layerName "," 
                    areaStr "," 
                    (rtos ptX 2 4) "," 
                    (rtos ptY 2 4)
                  ) 
                  fileHandle
                )
                
                ;; Delete the temporary region
                (vla-delete (car region))
              )
            )
            (setq i (1+ i))
          )
          
          ;; 5. Close file and notify user
          (close fileHandle)
          (princ (strcat "\nSuccess! " (itoa i) " polylines exported and labeled with Area. File saved to: " csvPath))
        )
        (princ "\nExport canceled. No file selected.")
      )
    )
    (princ "\nNo closed polylines selected.")
  )
  (princ)
)

(princ "\nType EXPORTCENTROIDS to run the command.")
(princ)
  tag

No comments:

Post a Comment