CADXChange

すべての LISP コマンド

CXTXT2CSV書き出しと取り込み(CSV)バージョン 1.0.0AutoCAD で動作確認済み

文字を CSV ファイルに書き出す

選択した文字を、画層、位置、高さ、内容とともに表計算用ファイルに書き出します。並びは上から下への読み順です。

使い方

  1. CXTXT2CSV と入力し、文字を選択します。
  2. 保存するファイルを選びます。ファイルダイアログがオフならファイル名を入力します。
  3. CSV を Excel などの表計算ソフトで開きます。

知っておくこと

  • 複数行文字は書式を除いて1行で書き出されます。

AutoCAD で読み込む

  1. ファイルを好きな場所に保存します。
  2. APPLOAD と入力し、ファイルを選んで「ロード」を押します。
  3. コマンド名を入力します:CXTXT2CSV。

起動のたびに使うには、同じ画面で「スタートアップ スイート」に追加するか、任意のローダーでフォルダーごと読み込みます。 任意のローダーについて

AutoCAD(フル版)で動作確認しています。AutoLISP を実行できるほかのソフトでも動く場合がありますが、確認はしていません。

コード

隠している部分のないテキストです。cxtxt2csv.lsp という名前のファイルにコピーするか、ダウンロードしてください。

;;; ============================================================================
;;; CXTXT2CSV - Export text to a CSV file
;;; Version 1.0.0
;;; CADXChange LISP tools - https://cadxchange.net/resources/lisp/cxtxt2csv
;;; Tested in: AutoCAD (full version). Other programs that run AutoLISP may work but are not tested.
;;; Copyright (c) CADXChange. Free for personal and commercial use; do not resell or
;;; republish it as a collection. Terms: https://cadxchange.net/legal/lisp-terms
;;; ============================================================================

;; CSV lines (header first) for the TEXT and MTEXT objects in NAMES: layer, x, y, height, text. MTEXT is written as
;; plain text with its line breaks turned into spaces. The rows run from the top of the drawing down, left to right
;; within a row (objects whose heights differ by less than half a text height count as one row).
(defun cx:txt2csv-lines (names / items ed mt)
  (foreach e names
    (setq ed (entget e)
          mt (= (cx:dxf 0 ed) "MTEXT"))
    (setq items (cons (list (cx:text-pt ed) (cx:dxf 8 ed) (cx:dxf 40 ed) (cx:replace (cx:text-plain (cx:text-get e) mt nil) "\n" " "))
                      items)))
  (setq items (cx:sort-grid (reverse items) 1 T 0 nil (if items (/ (caddr (car items)) 2.0) 1.0)))
  (cons "Layer,X,Y,Height,Text"
        (mapcar (function (lambda (i)
                  (cx:csv-line (list (cadr i) (cx:n4 (car (car i))) (cx:n4 (cadr (car i))) (cx:n4 (caddr i)) (cadddr i)))))
                items)))

(defun c:CXTXT2CSV ( / *error* cx:sv ss file)
  (setq *error* cx:err)
  (if (setq ss (cx:pick "\nSelect text: " '((0 . "TEXT,MTEXT"))))
    (if (setq file (cx:file-save "Save the text list as CSV" "text"))
      (cx:csv-save file (cx:txt2csv-lines (cx:ss->list ss)))))
  (princ))


;;; ---- Shared helpers (used by the command above; identical in every CADXChange tool) ----

(defun cx:dxf (code ed)
  (cdr (assoc code ed)))

;; The point a TEXT, MTEXT or ATTRIB sits at (the alignment point when it is aligned).
(defun cx:text-pt (ed)
  (if (and (member (cx:dxf 0 ed) '("TEXT" "ATTRIB" "ATTDEF"))
           (or (/= 0 (cx:dxf 72 ed)) (/= 0 (cx:dxf 73 ed)))
           (cx:dxf 11 ed))
    (cx:dxf 11 ed)
    (cx:dxf 10 ed)))

;; Replace every OLD in STR by NEW (case sensitive).
(defun cx:replace (str old new / n out pos)
  (setq n (strlen old) out "" pos 1)
  (if (= n 0)
    str
    (progn
      (while (<= pos (1+ (- (strlen str) n)))
        (if (= (substr str pos n) old)
          (setq out (strcat out new) pos (+ pos n))
          (setq out (strcat out (substr str pos 1)) pos (1+ pos))))
      (strcat out (substr str pos)))))

;; Split a TEXT (MT = nil) or MTEXT (MT = T) string into ((T . "plain") (C . "format code") ...).
;; Codes are %%c-style symbols, and in MTEXT also \P, \f...; \H...; \S...; {, } and the like.
(defun cx:fmt-tokens (str mt / out plain i n c d j k)
  (setq out nil plain "" i 1 n (strlen str))
  (while (<= i n)
    (setq c (substr str i 1) k 0)
    (cond
      ((and (= c "%") (= (substr str (1+ i) 1) "%") (< (1+ i) n))
       (setq k (if (wcmatch (substr str (+ i 2) 1) "#") 5 3)))
      ((and mt (= c "\\"))
       (setq d (substr str (1+ i) 1))
       (cond
         ((= d "") (setq k 1))
         ((member d '("P" "X" "x" "L" "l" "O" "o" "K" "k" "~" "\\" "{" "}")) (setq k 2))
         ((member d '("U" "u")) (setq k 7))
         (T
          (setq j i)
          (while (and (<= j n) (/= (substr str j 1) ";")) (setq j (1+ j)))
          (setq k (if (<= j n) (1+ (- j i)) 2)))))
      ((and mt (or (= c "{") (= c "}"))) (setq k 1)))
    (if (> k 0)
      (progn
        (if (/= plain "") (setq out (cons (cons 'T plain) out) plain ""))
        (setq out (cons (cons 'C (substr str i k)) out) i (+ i k)))
      (setq plain (strcat plain c) i (1+ i))))
  (if (/= plain "") (setq out (cons (cons 'T plain) out)))
  (reverse out))

;; The visible text of a TEXT or MTEXT string. In MTEXT, \P becomes a line break (KEEPNL = T: the two characters \P are kept).
(defun cx:text-plain (str mt keepnl / out)
  (setq out "")
  (foreach tk (cx:fmt-tokens str mt)
    (cond
      ((= (car tk) 'T) (setq out (strcat out (cdr tk))))
      ((= (cdr tk) "\\P") (setq out (strcat out (if keepnl "\\P" "\n"))))
      ((= (cdr tk) "\\~") (setq out (strcat out " ")))
      ((member (cdr tk) '("\\\\" "\\{" "\\}")) (setq out (strcat out (substr (cdr tk) 2))))))
  out)

;; The text of a TEXT, ATTRIB, ATTDEF or MTEXT (MTEXT keeps its codes).
(defun cx:text-get (ename / ed s)
  (setq ed (entget ename))
  (if (= (cx:dxf 0 ed) "MTEXT")
    (progn
      (setq s "")
      (foreach p ed (if (= (car p) 3) (setq s (strcat s (cdr p)))))
      (strcat s (cx:dxf 1 ed)))
    (cx:dxf 1 ed)))

;; Merge sort of LST with PRED (a function of two items that is true when the first goes first).
(defun cx:sort (lst pred / half a b out)
  (cond
    ((or (null lst) (null (cdr lst))) lst)
    (T
     (setq half (/ (length lst) 2) a nil b lst)
     (repeat half (setq a (cons (car b) a) b (cdr b)))
     (setq a (cx:sort (reverse a) pred) b (cx:sort b pred) out nil)
     (while (and a b)
       (if (apply pred (list (car b) (car a)))
         (setq out (cons (car b) out) b (cdr b))
         (setq out (cons (car a) out) a (cdr a))))
     (append (reverse out) a b))))

;; Sort ITEMS ((point . data) ...) into rows or columns: first by AXIS1 (0 = X, 1 = Y; DESC1 = T for large to small),
;; items whose AXIS1 values differ by less than TOL stay in one group, and each group is sorted by AXIS2.
(defun cx:sort-grid (items axis1 desc1 axis2 desc2 tol / sorted groups cur ref out)
  (setq sorted (cx:sort items
                 (function (lambda (a b)
                   (if desc1
                     (> (nth axis1 (car a)) (nth axis1 (car b)))
                     (< (nth axis1 (car a)) (nth axis1 (car b))))))))
  (foreach it sorted
    (if (and cur (<= (abs (- (nth axis1 (car it)) ref)) tol))
      (setq cur (cons it cur))
      (progn
        (if cur (setq groups (cons (reverse cur) groups)))
        (setq cur (list it) ref (nth axis1 (car it))))))
  (if cur (setq groups (cons (reverse cur) groups)))
  (foreach g (reverse groups)
    (setq out (append out
                (cx:sort g
                  (function (lambda (a b)
                    (if desc2
                      (> (nth axis2 (car a)) (nth axis2 (car b)))
                      (< (nth axis2 (car a)) (nth axis2 (car b))))))))))
  out)

;; 1-based position of SUB in STR at or after START, or nil.
(defun cx:find (str sub start / n i r)
  (setq n (strlen sub) i start r nil)
  (if (> n 0)
    (while (and (not r) (<= i (1+ (- (strlen str) n))))
      (if (= (substr str i n) sub) (setq r i))
      (setq i (1+ i))))
  r)

;; One CSV field: quoted when it holds a comma, a quote or a line break.
(defun cx:csv-field (s)
  (if (or (cx:find s "," 1) (cx:find s "\"" 1) (cx:find s "\n" 1) (cx:find s "\r" 1))
    (strcat "\"" (cx:replace s "\"" "\"\"") "\"")
    s))

(defun cx:join (lst delim / out)
  (setq out "")
  (foreach s lst
    (setq out (if (= out "") s (strcat out delim s))))
  (if lst out ""))

(defun cx:csv-line (fields)
  (cx:join (mapcar 'cx:csv-field fields) ","))

;; Real X as text with at most PREC decimals and no trailing zeros ("2.50" -> "2.5", "3.00" -> "3").
(defun cx:num (x prec / s)
  (setq s (rtos x 2 prec))
  (if (wcmatch s "*.*")
    (progn
      (while (= (substr s (strlen s)) "0") (setq s (substr s 1 (1- (strlen s)))))
      (if (= (substr s (strlen s)) ".") (setq s (substr s 1 (1- (strlen s)))))))
  (if (or (= s "-0") (= s "")) "0" s))

;; A real as text with at most 4 decimals.
(defun cx:n4 (x) (cx:num x 4))

;;; Geometry helpers: polylines with arcs, length, area, centroid, a point inside a shape.
;;; See helpers.lsp for the format.

;; Close the undo step and put the system variables back.
(defun cx:end ()
  (foreach v cx:sv (setvar (car v) (cdr v)))
  (command "_.UNDO" "_End")
  (setq cx:sv nil)
  (princ))

;; Error handler: restores everything, stays quiet on Esc.
(defun cx:err (msg)
  (if (> (getvar "CMDACTIVE") 0) (command))
  (cx:end)
  (if (and msg (not (wcmatch (strcase msg) "*BREAK*,*CANCEL*,*EXIT*")))
    (princ (strcat "\nError: " msg)))
  (princ))

;; Use the objects already selected, or ask the user to select; FILTER is an ssget filter list or nil.
(defun cx:pick (msg filter / ss)
  (setq ss (if filter (ssget "_I" filter) (ssget "_I")))
  (if (null ss)
    (progn
      (princ msg)
      (setq ss (if filter (ssget filter) (ssget)))))
  ss)

;; Ask where to save a CSV file; BASE is the proposed file name without folder and extension. Returns a path or nil.
;; With FILEDIA 0 the name is typed at the command line instead of picked in a dialog.
(defun cx:file-save (title base / def f)
  (setq def (strcat (getvar "DWGPREFIX") base ".csv"))
  (if (= (getvar "FILEDIA") 0)
    (progn
      (setq f (getstring T (strcat "\n" title " <" def ">: ")))
      (if (= f "") def f))
    (getfiled title def "csv" 1)))

;; Write LINES to FILE; returns T, or nil when the file cannot be written.
(defun cx:write-lines (file lines / f)
  (if (setq f (open file "w"))
    (progn
      (foreach l lines (write-line l f))
      (close f)
      T)))

;; Write CSV LINES to FILE and report it; returns T when the file was written.
(defun cx:csv-save (file lines)
  (if (cx:write-lines file lines)
    (progn (princ (strcat "\n" (itoa (1- (length lines))) " row(s) written to " file)) T)
    (progn (princ (strcat "\nThe file could not be written: " file)) nil)))

;; Selection set to a list of entity names.
(defun cx:ss->list (ss / i out)
  (setq i 0)
  (if ss
    (repeat (sslength ss)
      (setq out (cons (ssname ss i) out)
            i   (1+ i))))
  (reverse out))

(princ "\nCXTXT2CSV loaded. Type CXTXT2CSV to start.")
(princ)

バージョン履歴

バージョン 1.0.0 · 2026年10月27日

最初のリリース。

たくさんの図面にまとめて使いたい?

TextSync なら、フォルダー内の図面すべてに対してこの種の作業を一度に行えます。

TextSync

ほかのコマンド:書き出しと取り込み(CSV)