Announcements

The Autodesk Community Forums has a new look. Read more about what's changed on the Community Announcements board.

Bulk export tables to excel

cbrackettZDB
Explorer

Bulk export tables to excel

cbrackettZDB
Explorer
Explorer

Is it possible to Bulk Export multiple tables to an Excel format all at once without having to do each individual table? I am familiar with the TABLEEXPORT command, however, it only does a single table at a time. I have multiple drawings that have nearly 100 tables where I am using Tables to display data. If there is an ability to achieve this it would be greatly appreciated.

 

attached is a DWG with the tables as well as other items. No personal information is listed in the DWG. 

 

AutoCAD 2023

0 Likes
Reply
1,031 Views
13 Replies
Replies (13)

MrJSmith
Advocate
Advocate

Funny, I was just looking into this. My coworker ran into a similar issue but ultimately did it by hand as he only had ~20 or so tables. 

 

I don't like the tableexport function doesn't take in account merged cells or widths despite the fact that information is contained in the table. Also it makes it a CSV rather than excel file, which I thought was another missed opportunity. 

 

If no one has something already written, I'll throw something up in the next day or two.

0 Likes

cbrackettZDB
Explorer
Explorer
It would be nice if it could atleast have an option in the DATAEXTRACTION utility. Itโ€™s nearly setup for it already, just needs the Table option.

I did find an Add-on tool that does it in bulk, however it also does not maintain merged cells or sizes.

Tool name in Autodesk App Store: Tablebuilder 64 bit
0 Likes

MrJSmith
Advocate
Advocate

Strange, it claims it does....

ยท  What you see in AutoCAD is what you get in Excel.

ยท  Support for merged cells in the AutoCAD table.

ยท  Support for the double-line border in the AutoCAD table.

0 Likes

hosneyalaa
Advisor
Advisor

@cbrackettZDB 

HI , TRY

;---------------------------------------------------------------------------------------------------------------------------------
;-------------------------------------- GATHERING TABLE INFORMATION ------------------------------------
;---------------------------------------------------------------------------------------------------------------------------------
(defun tableinfo ( ss  / n entlist)
 (setq n 0)
 (repeat (sslength otcontents)
   (setq entlist (entget (ssname otcontents n)))
   (cond ((member (cdr (assoc 0 entlist)) '("LINE" "POLYLINE"))
             (getlinepts entlist)(setq linelist (cons (ssname otcontents n) linelist)))
            ((member (cdr (assoc 0 entlist)) '("TEXT" "MTEXT"))
             (setq textlist (cons (ssname otcontents n) textlist)))
            ((member (cdr (assoc 0 entlist)) '("INSERT"))
             (setq blocklist (cons (ssname otcontents n) blocklist)))
   )
   (setq n (1+ n))
 )
)
;;;(PRINC blocklist)
;;;(PRINC textlist)
;;;(PRINC linelist)
;-------------------------- Cell Count/Height/Width Determination ----------------------
;;Gathers x and y positions of lines and polylines in separate lists
;;This is used to determine height/width & # of rows/columns
;;Line info must be gathered first in order to determine
;;cell position of any other gathered information
;---------------------------------------------------------------------------------------
(defun getlinepts (alist / x  xpt ypt)
  (foreach x alist
     (if (member (car x) '(10 11))
         (progn
           (if (not (vl-position (setq xpt (atof (rtos (car (trans (cdr x) 0 1)) 2 2))) lpxlist))
               (setq lpxlist (cons xpt lpxlist)))
           (if (not (vl-position (setq ypt (atof (rtos (cadr (trans (cdr x) 0 1)) 2 2))) lpylist))
               (setq lpylist (cons ypt lpylist)))
         )        
      )
   )
);defun
;---------------------------- Text Info and Cell Position -----------------------------------------------------
;;Determine cell position by insertionpoint of text objects
;;(Using text center is probably more reliable)
;;Create list of indexed lists containing "Order", "Position", "Content", "Height", "Rotation", "StyleName" and "TrueColor"
;;to be used to fill acad table after creation
;;If row and column is already in list, replace with combined string
;--------------------------------------------------------------------------------------------------------------
(defun gettxtinfo (alist / x vlaobj pos rpos cpos expos)
(setq vlaobj (vlax-ename->vla-object txt)
        pos (trans (midp vlaobj) 0 1);Midpoint
        rpos (1- (vl-position (cadr pos)(vl-sort (cons (cadr pos) lpylist) '>)));Row Position
        cpos (1- (vl-position (car pos) (vl-sort (cons (car pos) lpxlist) '<))));Column Position
(if (setq expos (vl-position (list rpos cpos) (mapcar '(lambda (x)(cdr (assoc "Position" x))) tinfo)));if cell is taken
   (setq tinfo
     (replace tinfo expos
      (replace
       (nth expos tinfo)
        2
        (cons "Content"
       (if (> (cadr pos) (cdr (assoc "Order" (nth expos tinfo))));in order according to y position
          (strcat (vla-fieldcode vlaobj) " " (cdr (assoc "Content" (nth expos tinfo))))
          (strcat (cdr (assoc "Content" (nth expos tinfo))) " " (vla-fieldcode vlaobj))
       )))))
(setq tinfo
 (cons
  (list
   (Cons "Order" (cadr pos))
   (Cons "Position" (list rpos cpos));Position
   (Cons "Content" (vla-fieldcode vlaobj));Content
   (Cons "Height" (vla-get-height vlaobj))
   (Cons "Rotation" (vla-get-rotation vlaobj))
   (Cons "StyleName" (vla-get-StyleName vlaobj))
   (Cons "TrueColor"
    (if
     (= (vla-get-colorindex (vla-get-truecolor vlaobj)) 256)
      (vla-get-truecolor
       (vla-item
        (vla-get-layers ActDoc)
        (vla-get-layer vlaobj)))
      (vla-get-truecolor vlaobj)
    )
  )
 )
tinfo)))
;(vla-delete vlaobj)
);defun
;--------------------------- Block Info and Cell Position -------------------------------------------------------
;;Gather block information
;;determine cell position according to insertion point
;;Create an indexed list of lists containing "Position" (row, column), "ObjID",
;;"Attributes" (attribute id, attributetextstring) and "Scale" 
;----------------------------------------------------------------------------------------------------------------
(defun getblockinfo (obj / pos rpos cpos bname objid bobj attid)
  (if (= (type obj) 'ename)
    (setq obj (vlax-ename->vla-object obj))
  )
(setq pos (trans (midp obj) 0 1)
        rpos (1- (vl-position (cadr pos)(vl-sort (cons (cadr pos) lpylist) '>)));Row Position
        cpos (1- (vl-position (car pos) (vl-sort (cons (car pos) lpxlist) '<)));Column Position
        bname (vla-get-name obj);Block Name
        bobj (vla-item (vla-get-blocks ActDoc) bname));Block Vla Object
(vlax-for i bobj ; Foreach item in block
(if (eq (vla-get-objectname i) "AcDbAttributeDefinition");If item is an attribute
  (setq attid (append attid (list (vla-get-objectid i))));List Attribute Id
)
)
(setq objid (vla-get-objectid bobj));Block Object Id
 (setq binfo
   (cons
    (list
     (Cons "Name" bname)
     (Cons "Position" (list rpos cpos))
     (Cons "ObjID" objid)
  (if (= (vla-get-hasattributes obj) :vlax-true)
   (Cons "Attributes"
    (reverse
    (mapcar
      '(lambda (x y) (cons y (vla-get-textstring x)))
      (vlax-safearray->list (variant-value (vla-getattributes obj)))
      attid
    )
    )
   )
  )
     (Cons "Scale" (vla-get-xscalefactor obj))
    )
binfo))
)
;------------------------------------------------------------------------------------------------------------------------
;-------------------------------------------- REPLACE by Charles Alan Butler---------------------------------------------
;;Cab's replace function used in this routine to avoid overwriting cells and to update cell merge lists
;------------------------------------------------------------------------------------------------------------------------
(defun replace (lst i itm)
  (setq i (1+ i))
  (mapcar
    '(lambda (x)
      (if (zerop (setq i (1- i))) itm x)
    )
    lst
  )
)

;-------------------------Midpoint-----------------
(defun midp (obj / ObjLl ObjUr)
 (vla-GetBoundingBox obj 'ObjLl 'ObjUr)
 (mapcar
  '(lambda (a b) (/ (+ a b) 2.0))
   (safearray-value ObjLl)
   (safearray-value ObjUr))
)

;-------------------------Q&D Number Accumulation---------------------------
;Used in this routine for polar distances to determine which cells to merge.
;;Recursive function possible. Ask Gile (recursion master) if desired.
(defun acnumlist (nlist / acnlist)
 (repeat (length nlist)
  (setq acnlist (cons (apply '+ nlist) acnlist)
        nlist (reverse (cdr (reverse nlist))))
 )
 acnlist
)
;--------------------------------------------------------------------------
;; รธ Remove_nth รธ  (Lee Mac)          ;;
;; ~ Removes the nth item in a list.  ;;

(defun Remove_nth (i lst / j)
  (setq j -1)
  (vl-remove-if
    (function
      (lambda (x)
        (eq i (setq j (1+ j))))) lst))


 ;;; private function (fixo)
(defun setcelltext(cells row column value)
  (vl-catch-all-apply
    'vlax-put-property
    (list cells 'Item row column
	 (vlax-make-variant
	   (vl-princ-to-string value) 8)))
  )

  (defun setgridlines(xlapp range);(fixo)
  ;; select the range:
  (vlax-invoke-method range 'Select)
  ;; get excel application selection property:  
  (setq range (vlax-get-property xlapp 'Selection))
  ;; get selection borders
  (setq borders (vlax-get-property range 'Borders))
  ;; iterate through all edges of the selection
  (setq cnt 0)
    (vlax-for a	 borders
      (setq cnt (1+ cnt))
      (vl-catch-all-apply
	(function
	  (lambda ()
	    (progn
	      (if (< cnt 5)
		(progn
		  (vlax-put-property
		    a
		    'LineStyle
		    (vlax-make-variant 1 3)); single line style
		  (vlax-put-property
		    a
		    'Weight
		    (vlax-make-variant 2 3));  lines
		  (vlax-put-property
		    a
		    'ColorIndex
		    (vlax-make-variant 1 5))); color black
		
		;; turn off the diagonal lines:
		(vlax-put-property a 'LineStyle (vlax-make-variant -4142 3))
		)
	      )
	    )
	  )
	)
      )
  (princ)
  )

(defun conexcelcolumn (/ a b list1);(Q. J. Chen)
  (setq a 65)
  (setq list1 nil)
  (repeat 26
    (setq list1 (append
		  list1
		  (list (chr a))
		)
    )
    (setq a (1+ a))
  )
  (setq a 65)
  (repeat 26
    (setq b 65)
    (repeat 26
      (setq list1 (append
		    list1
		    (list (strcat (chr a) (chr b)))
		  )
      )
      (setq b (1+ b))
    )
    (setq a (1+ a))
  )

  list1
)

  
 ;;; private function
 ;;;  apply props
(defun Orient (xlrange)
  (mapcar '(lambda (prop value)
	     (vl-catch-all-apply
	       'vlax-put-property
	       (list xlrange
		     prop
		     value
	       )
	     )
	   )

	  (list	'HorizontalAlignment 'VerticalAlignment 'Orientation)

	  (list -4143 -4108 (cvunit (cdr (assoc "Rotation" x)) "radian" "degree"))
  )

)

;---------------------------------------------------------------------------------------------------------------------
;------------------------------------------- CONVERT OLD TABLE ROUTINE -----------------------------------------------
;---------------------------------------------------------------------------------------------------------------------
(defun c:TE (/ ActDoc   *error* orerror otcontents textlist    colwidths i mlist  p0 hmergelist2 vmergelist2
                       *Space*  lpxlist lpylist  tinfo     cwidths     check        tstyle     spos newstring
                       tstylelst blocklist  rowheights selsets       tstylelst2 tstylelst3
                       kword     linelist       binfo        rheights   hmergelist vmergelist  ssitem   tblobj mb   
                       colorlst colorlst2 th tr ts tc newstyle RowTypes a acapp acsp address adoc atable borders cnt col data_list fname font prop release row
	       selrange sset txt_list urange value xlapp xlbook xlbooks xlcells xlrange xlsheet xlsheets)
                
(vl-load-com)
(setq oerror *error*)
(defun *error* ( msg )
        (princ (strcat "\n<" msg ">\n"))
	(mapcar '(lambda (x)(and x (not (vlax-object-released-p x))(vlax-release-object x))) (list ssitem)) 
        (setq *error* oerror)
        (setvar 'nomutt 0)
	(vla-EndUndoMark ActDoc)
        (princ)
);defun *error*
(setq ActDoc (vla-get-activedocument (vlax-get-acad-object))
        *Space* (vlax-get-property ActDoc (nth (vla-get-ActiveSpace ActDoc)'("PaperSpace" "ModelSpace"))))

(vla-EndUndoMark ActDoc)
(vla-StartUndoMark ActDoc)

(setq otcontents (ssget))
(command "._zoom" "object" otcontents "")
(princ "\nSorting Line Info...")
(tableinfo otcontents)
(setq lpxlist (vl-sort lpxlist '<) lpylist (vl-sort lpylist '>)) 
(princ "\nSorting Text Info...")                                   
(mapcar '(lambda (txt)(gettxtinfo (entget txt))(redraw txt 2)) textlist);;using redraw function To avoid interference 
(princ "\nSorting Block Info...")             
(mapcar '(lambda (blk)(getblockinfo blk)) blocklist)   
(setq colwidths (mapcar '(lambda (x)(- (nth (1+ (vl-position x lpxlist)) lpxlist) x))(reverse (cdr (reverse lpxlist))))
      rowheights (mapcar '(lambda (x)(- x (nth (1+ (vl-position x lpylist)) lpylist)))(reverse(cdr (reverse lpylist)))))
(setq p0 (vlax-3d-point (trans (list (car lpxlist) (car lpylist) 0.0) 1 0)));;<---Table Placement (Currently using Top Left corner)
(progn
(princ "\nSearching for merged cells...") 
(princ)
(setvar 'nomutt 1)
;-----------------------------------Method to determine which cells to merge--------------------------------------------
;Method fails if missed selection is not possible at zoom level.
;To determine which cells to merge, a selection at point is used.
;For each row, a selection is attempted at each vertical line at row's center.
;If no selection is made, the point is at the center or left of horizontally merged cells.
;For each column, a selection is attempted at each horizontal line at column's center.
;If no selection is made, the point is at the center or upper region of vertically merged cells.
;Continuation of merging is determined by a 'consecutive miss'.
;When a 'consecutive miss' is made, max column/row item is replaced by the next column/row.
;-----------------------------------------------------------------------------------------------------------------------
(setq selsets (vla-get-selectionsets ActDoc))
(vl-catch-all-error-p (vl-catch-all-apply 'vla-add (list selsets "InxCheckSet")))
(setq ssitem (vla-item selsets "InxCheckSet")
        cwidths (acnumlist colwidths)
        rheights (acnumlist rowheights));;col widths & row heights accumulated for polar use
(mapcar '(lambda (pt rh)
 (mapcar '(lambda (x)
   (vl-catch-all-error-p (vl-catch-all-apply 'vla-clear (list ssitem)))
   (vla-selectatpoint ssitem (vlax-3d-point (polar (list (car lpxlist) (+ pt (/ rh 2)) 0.0) 0 x)))
   (if (zerop (vla-get-count ssitem))
         (if check
           (setq hmergelist (replace hmergelist 0 (replace mlist 3 (1+ (vl-position x cwidths)))))
           (setq hmergelist
            (cons
             (setq mlist
               (list
                 (1- (vl-position pt lpylist))
                 (vl-position x cwidths)
                 (1- (vl-position pt lpylist))
                 (1+ (vl-position x cwidths))
               )) hmergelist)
             check T)
         );if
       (setq check nil mlist nil)
   ));lambda
   cwidths
  );mapcar
);lambda
(member (nth 1 lpylist) lpylist)
rowheights
);mapcar

(mapcar '(lambda (pt cw)
  (mapcar '(lambda (x)
    (vl-catch-all-error-p (vl-catch-all-apply 'vla-clear (list ssitem)))
    (vla-selectatpoint ssitem (vlax-3d-point (polar (list (+ pt (/ cw 2)) (car lpylist) 0.0) (* pi 1.5) x)))
    (if (zerop (vla-get-count ssitem))
         (if check
           (setq vmergelist (replace vmergelist 0 (replace mlist 2 (1+ (vl-position x rheights)))))
           (setq vmergelist
            (cons
             (setq mlist
               (list
                 (vl-position x rheights)
                 (vl-position pt lpxlist)
                 (1+ (vl-position x rheights))
                 (vl-position pt lpxlist)
               )) vmergelist)
             check T)
         );if
       (setq check nil mlist nil)
   ));lambda
   rheights
  );mapcar
);lambda
lpxlist
colwidths
);mapcar

(setvar 'nomutt 0)
);progn
(setq hmergelist2 (mapcar '(lambda (b)(list (car b)(cadr b))) hmergelist))
(setq vmergelist2 (mapcar '(lambda (b)(list (car b)(cadr b))) vmergelist))

(mapcar
'(lambda (a / expos)
  (if
   (setq expos (vl-position (list (car a)(cadr a)) vmergelist2))
   (setq dmergelist (cons (list (car a)(cadr a)(caddr (nth expos vmergelist))(cadddr a)) dmergelist))))
   hmergelist
)

(setq	xlapp	   (vlax-get-or-create-object "Excel.Application");(fixo)
	xlbooks  (vlax-get-property xlapp 'Workbooks)
	xlbook	   (vlax-invoke-method xlbooks 'Add)
	xlsheets (vlax-get-property xlbook 'Sheets)
	xlsheet	   (vlax-get-property xlsheets 'Item 1)
	xlcells	   (vlax-get-property xlsheet 'Cells)
	)
(vla-put-visible xlapp :vlax-true)
(vlax-invoke-method xlsheet "Activate")
(setq ecol (conexcelcolumn))
;place text
(mapcar '(lambda (x / r c xlrange)
         (setq r (1+ (cadr (assoc "Position" x))) c (1+ (caddr (assoc "Position" x))))
         (setcelltext xlcells r c (cdr (assoc "Content" x)))
         (setq xlRange (vlax-get-property xlsheet "Range" (strcat (nth (1- c) ecol) (itoa r))))
         (vlax-invoke-method xlRange "Select")
         (setq xlRange (vlax-get-property xlapp "Selection"))
         (Orient xlrange)
         )
         tinfo
)
;place block info
(mapcar '(lambda (x / r c bstring)
         (setq r (1+ (cadr (assoc "Position" x))) c (1+ (caddr (assoc "Position" x))))
         (setq bstring "")
         (if (cdr (assoc "Attributes" x))
         (progn
         (mapcar
          '(lambda (y )
           (setq bstring (strcat ":"(cdr y) bstring)))
           (cdr (assoc "Attributes" x)))
         (setcelltext xlcells r c (strcat "Block:"(cdr (assoc "Name" x)) bstring))
         ));if
         )
         binfo
)
;merge cells

 

(princ "\nProcessing Merge Info")
;-------------------------------------------------------------------------------------------------------------------------
(defun convertlist ( mrglist / newmrglist)
  (foreach x mrglist 
   (setq newmrglist (append newmrglist (list (strcat (nth (cadr x) ecol)(itoa (1+ (car x)))":" (nth (cadddr x) ecol)(itoa (1+ (caddr x)))))))
  )
)

(defun applylist ( mrglist / xlRange)
 (foreach x mrglist
 (setq xlRange (vlax-get-property xlsheet "Range" x))
 (vlax-invoke-method xlRange "Select")
 (setq xlRange (vlax-get-property xlapp "Selection"))
 (vlax-put-property xlRange "MergeCells" :vlax-true)
 )
)

(setq hmergelist2 (convertlist hmergelist)
      vmergelist2 (convertlist vmergelist))
(applylist hmergelist2)
(applylist vmergelist2)
 (vlax-invoke-method
   (vlax-get-property xlsheet 'Columns)
   'AutoFit)
;;;  align all columns to center
   (vlax-put-property
     (setq urange(vlax-get-property xlsheet 'UsedRange))
   'HorizontalAlignment -4108)
;;;  draw grid lines
  (setgridlines xlapp urange)

 (mapcar '(lambda (x);(fixo)
	     (vl-catch-all-apply
	       '(lambda	()
		  (vlax-release-object x)
		)
	     )
	   )
	  (list xlcells xlsheet xlsheets xlbook xlbooks xlapp)
  )
  (setq  xlapp nil)
  (gc)(gc)(gc)
(mapcar '(lambda (x)(and x (not (vlax-object-released-p x))(vlax-release-object x))) (list ssitem)) 
(mapcar '(lambda (txt)(redraw txt 1)) textlist);;using redraw function again
(setq *error* oerror)
(vla-EndUndoMark ActDoc)
(princ)
(princ)
);defun

 

70.gif

0 Likes

Sea-Haven
Mentor
Mentor

Maybe this export table to Excel. I can see a issue with doing lots of tables, do you want 1 worksheet per table can be added its 1 line of code. Or a simpler is (setq row (1+ row)) so it leaves 1 blank line, did this for some plines dump.

 

Your welcome to modify it or ask for help. It only does one now but need a loop at the "select table". It opens Excel so dont have open. If open will add a worksheet.

 

 

 

 

; simple table to excel
; expects Title header and data
; BY Alanh Jan 2022
; do not have excel open

(defun c:tab2excel ( /  x y z AH:putcell Ah:opennew number2alpha obj cols row)

(defun AH:putcell (cellname val1 / )
(setq myRange (vlax-get-property  (vlax-get-property myxl "ActiveSheet") "Range" cellname))
(vlax-put-property myRange 'Value2 val1)
)

(defun AH:opennew ( /  )
(if (= (setq myxl (vlax-get-object "Excel.Application") ) nil)
(setq myxl (vlax-get-or-create-object "excel.Application"))
)
(vla-put-visible myXL :vlax-true)
(vlax-put-property myxl 'ScreenUpdating :vlax-true)
(vlax-put-property myXL 'DisplayAlerts :vlax-true)
)

; Number2Alpha - Converts Number into Alpha string
; Function By: Gilles Chanteau from Marseille, France
; Arguments: 1
;   Num# = Number to convert
; Syntax example: (Number2Alpha 731) = "ABC"
;-------------------------------------------------------------------------------
(defun Number2Alpha (Num# / Val#)
  (if (< Num# 27)
    (chr (+ 64 Num#))
    (if (= 0 (setq Val# (rem Num# 26)))
      (strcat (Number2Alpha (1- (/ Num# 26))) "Z")
      (strcat (Number2Alpha (/ Num# 26)) (chr (+ 64 Val#)))
    )
  )
);defun Number2Alpha

(AH:opennew)
(vlax-invoke-method (vlax-get-property myXL 'WorkBooks) 'Add)

(setq obj (vlax-ename->vla-object (car  (entsel "Pick table "))))
(setq cols (vla-get-columns obj))
(setq rows (vla-get-rows obj))
(alert (strcat (rtos rows 2 0) " rows " (rtos cols 2 0) " columns \n will now send to excel "))

(if (not AH:Toggs)(load "Multi toggles.lsp"))
(setq ans (reverse (ah:toggs   '("Please choose " "Title " "Heading " "Data"))))


(If (= "1" (nth 0 ans))
(AH:putcell "A1" (vla-getText Obj 0 0 ))
)

(if (= "1" (nth 1 ans))
(progn
(setq x 1 y 1 z 2)
(repeat cols
(AH:putcell (strcat (Number2Alpha x) (rtos z 2 0)) (vla-getText Obj y (- x 1)  ))
(setq x (1+ x))
)
)
)

(if (= "1" (nth 2 ans))
(progn
(setq y 2)
(repeat (- rows 2)
(setq x 1 )
(repeat cols
(AH:putcell (strcat (Number2Alpha x) (rtos (+ y 1) 2 0)) (vla-getText Obj y (- x 1)  ))
(setq x (1+ x))
(princ (strcat "\nRow " (rtos y 2 0)))
)
(setq y (1+ y))
)
)
)

(vlax-release-object myXL)
(alert "Please save the excel and close if you want to import another table ")

(princ)
)
(c:tab2excel)

 

 

Need loop here select table

 

 

; (vlax-invoke-method (vlax-get-property myXL 'WorkBooks) 'Add)

(while (setq tabex (car  (entsel "Pick table ")))
(setq obj (vlax-ename->vla-object tabex))
(vlax-invoke-method (vlax-get-property myXL 'WorkBooks) 'Add)
..............
...........

) 
; end while 

 

So how do you want to do the excels.

 

0 Likes

cbrackettZDB
Explorer
Explorer

I am not Familiar with the Code you provided or how to use it properly. However, you have achieved the Table Export, but does that same process in your gif need to be done to all of the Tables? EXPLODE (X) 3 times, use TEXTEDIT (TE), and finally a Copy & Paste?

0 Likes

cbrackettZDB
Explorer
Explorer

If I could get the Excel to all be in 1 workbook That would be ideal. maybe add a single line space between them for easy reading?

0 Likes

Sea-Haven
Mentor
Mentor

Been away fishing for a few days will add to my to do list to select multiple tables.

0 Likes

Sea-Haven
Mentor
Mentor

I have added pick multi tables so give it a try.

 

; simple table to excel
; expects Title header and data
; BY Alanh Oct  2023
; do not have excel open
; updated for multiple tables

(defun c:tab2excel ( /  x y z AH:putcell Ah:opennew number2alpha obj cols row)

;;	Thanks to fixo			;;
;;   = Set Excel cell text =    ;;
;;				;;
(defun xlsetcelltext ( row column text)
(setq cells (vlax-get-property  (vlax-get-property myxl "ActiveSheet") "Cells"))
  (vl-catch-all-apply
    'vlax-put-property
    (list cells 'Item row column
	(vlax-make-variant (vl-princ-to-string text) vlax-vbstring)))
)

(defun AH:opennew ( /  )
(if (= (setq myxl (vlax-get-object "Excel.Application") ) nil)
(setq myxl (vlax-get-or-create-object "excel.Application"))
)
(vla-put-visible myXL :vlax-true)
(vlax-put-property myxl 'ScreenUpdating :vlax-true)
(vlax-put-property myXL 'DisplayAlerts :vlax-true)
(vlax-invoke-method (vlax-get-property myXL 'WorkBooks) 'Add)
)

(if (= myxl nil)(AH:opennew))

(setq row 1 col 1)
(while (setq tab (car  (entsel "Pick table or enter to exit ")))
(setq obj (vlax-ename->vla-object tab))

(setq cols (vla-get-columns obj))
(setq rows (vla-get-rows obj))
(alert (strcat (rtos rows 2 0) " rows " (rtos cols 2 0) " columns \n will now send to excel "))

(if (not AH:Toggs)(load "Multi toggles.lsp"))
(setq ans (reverse (ah:toggs   '("Please choose " "Title " "Heading " "Data"))))


(If (= "1" (nth 0 ans))
 (progn
  (xlsetcelltext row 1 (vla-getText Obj 0 0))
  (setq row (1+ row))
 )
 (princ "\nSkip Title")
)
(if (= "1" (nth 1 ans))
 (progn
  (setq col 1 rowt 2)
  (if (= row nil)(setq row 1))
   (repeat cols
    (xlsetcelltext row col (vla-getText Obj 1 (- col 1)))
    (setq col (1+ col))
   )
 (setq row (1+ row))
 )
 (princ "Skip heading")
)
(if (= "1" (nth 2 ans))
 (progn
 (setq rowt 2)
  (repeat (- rows 2)
   (setq col 1)
   (repeat cols
    (xlsetcelltext row col (vla-getText Obj rowt (- col 1)  ))
    (setq col (1+ col))
   )
  (setq row (1+ row) rowt (1+ rowt))
  )
 (setq row (1+ row))
 )
)
(vlax-release-object obj)
(setq obj nil)
)

(vlax-release-object myXL)(setq myxl nil)

(alert "Please save the excel and close if you want to import other tables ")

(princ)
)
(c:tab2excel)

 Needs Multi toggles to be in a support path or change the (load "multi toggles to include full path of where its saved.

SeaHaven_0-1698025277284.png

 

 

0 Likes

eoconnor95662
Enthusiast
Enthusiast

This lsp should do the trick. Open the dwg drawing, then execute lisp while the dwg is active and in the pop-up navigate to the .dwg file location folder. Then type in the name of the excel document you want to contain all of the tables (only end it with .csv) and you will receive I file in the same directory like the file I also attached.

 

Happy Hunting!

0 Likes

hosneyalaa
Advisor
Advisor
0 Likes

cbrackettZDB
Explorer
Explorer

Update:
I don't want anyone to think I just left the conversation, work the last year has been very busy and this was just a side quest at the time. However, I am back in the saddle on this topic. I also wanted to thank everyone for the contributions and insights. I have also learned a lot more of AutoCAD's capabilities since the Original post, and now have a better understanding of many commands as well as how to Save and use LISPs. 

 

Couple of items:

@hosneyalaa I did try to use your LISP but trying to copy the whole thing was a task. I had to actually export the source code (F12 on Chrome) and copy it that way. I am not sure if that worked properly in the C&P due to this process. My Browser would crash when attempting to copy & paste normally.

 

@eoconnor95662 I also tried your LISP and it does function properly, however I may be missing something because I am only able to export 1 table at a time. 

 

@Sea-Haven I am not able to get your latest LISP to function. It may be something on my end. 

 

New Scope:

Export all the tables in a DWG to a single .csv file. If it is possible, have each cell be converted to a column and each table be listed as a Row. 

 

The purpose of this is to (Eventually) Import the CSV into ArcGIS and place pins based on the Latitude & Longitude. The current example DWG I Provided does not have these separated but Attached is an updated version with them separate as well as a CSV of the data in the format I am thinking would be the easiest. I know the DATA EXTRACTION command will do this, however I would have to XPLODE the table and the CSV does not keep every table seperate. DATA EXTRACTION also detects all the text if there is something else outside the table. 

 

Thank you guys again for all the help on this. I am sure I am not the only one who thinks this is an important Thread and I am sure there are many people who have used the LISPs you guys have provided in assisting with their own projects. 

 

The DWG is just the same table copied multiple times. 

0 Likes

Sea-Haven
Mentor
Mentor

Try this

; https://forums.autodesk.com/t5/visual-lisp-autolisp-and-general/bulk-export-tables-to-excel/td-p/12314891
; By Alan H dec 2024

(defun wow ( / ss fo obj rows cols str y x k)

;;-------------------=={ UnFormat String }==------------------;;
;;                                                            ;;
;;  Returns a string with all MText formatting codes removed. ;;
;;------------------------------------------------------------;;
;;  Author: Lee Mac, Copyright ยฉ 2011 - www.lee-mac.com       ;;
;;------------------------------------------------------------;;
;;  Arguments:                                                ;;
;;  str - String to Process                                   ;;
;;  mtx - MText Flag (T if string is for use in MText)        ;;
;;------------------------------------------------------------;;
;;  Returns:  String with formatting codes removed            ;;
;;------------------------------------------------------------;;

(defun LM:UnFormat ( str mtx / _replace rx )

    (defun _replace ( new old str )
        (vlax-put-property rx 'pattern old)
        (vlax-invoke rx 'replace str new)
    )
    (if (setq rx (vlax-get-or-create-object "VBScript.RegExp"))
        (progn
            (setq str
                (vl-catch-all-apply
                    (function
                        (lambda ( )
                            (vlax-put-property rx 'global     actrue)
                            (vlax-put-property rx 'multiline  actrue)
                            (vlax-put-property rx 'ignorecase acfalse) 
                            (foreach pair
                               '(
                                    ("\032"    . "\\\\\\\\")
                                    (" "       . "\\\\P|\\n|\\t")
                                    ("$1"      . "\\\\(\\\\[ACcFfHLlOopQTW])|\\\\[ACcFfHLlOopQTW][^\\\\;]*;|\\\\[ACcFfHLlOopQTW]")
                                    ("$1$2/$3" . "([^\\\\])\\\\S([^;]*)[/#\\^]([^;]*);")
                                    ("$1$2"    . "\\\\(\\\\S)|[\\\\](})|}")
                                    ("$1"      . "[\\\\]({)|{")
                                )
                                (setq str (_replace (car pair) (cdr pair) str))
                            )
                            (if mtx
                                (_replace "\\\\" "\032" (_replace "\\$1$2$3" "(\\\\[ACcFfHLlOoPpQSTW])|({)|(})" str))
                                (_replace "\\"   "\032" str)
                            )
                        )
                    )
                )
            )
            (vlax-release-object rx)
            (if (null (vl-catch-all-error-p str))
                str
            )
        )
    )
)

(prompt "Select tables")
(setq ss (ssget '((0 ."acad_table"))))
(setq fo (open (setq fname "d:\\acadtemp\\tables.csv") "w"))
(if (= ss nil)(progn (alert "No tables selected \n\n will now exit ")))

(repeat (setq k (sslength ss))
  (setq obj (vlax-ename->vla-object (ssname ss (setq k (1- k)))))
  (setq rows (vlax-get obj 'rows))
  (setq cols (vlax-get obj 'columns))
  (setq y 0)
  (repeat rows
   (setq x 0)
   (setq str (vla-gettext obj y x))
   (setq str (LM:UnFormat str nil))
   (repeat (- cols 1)
    (setq str (strcat str "," (LM:UnFormat (vla-gettext obj Y (setq x (1+ x))) nil)))
   )
   (write-line str fo)
   (setq y (1+ y))
   )
  (write-line ",,,," fo)
)

(close fo)
(princ)
)
(startapp "EXCEL" fname)
(wow)
0 Likes