You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

AutoLisp实现CAD块属性ID、实例数导入现有Excel的开发咨询

AutoLISP 实现CAD块属性统计写入Excel自动化方案

实现步骤

1. 建立属性ID与Excel行的固定映射

直接用AutoLISP原生关联表存储200组映射,查询效率高,修改方便:

;; 映射表格式:(("属性ID" . 对应Excel行号) ...),按实际需求补全所有200组映射即可
(setq *id-row-mapping*
  '(
    ("A001" . 2)
    ("A002" . 3)
    ("A006" . 10)
    ;; 其余映射按上述格式补充
  )
)

后续通过(assoc "目标ID" *id-row-mapping*)即可快速获取对应行号。

2. 统计属性ID对应块的实例数

复用已有Lee Mac的块属性提取逻辑,构建计数关联表:

;; 入参:属性标签名称(根据你的块属性实际命名修改,示例为"ID")
;; 返回值:(("属性ID" . 实例计数) ...)格式的统计结果关联表
(defun count-block-by-id (attrib-tag / blk-col blk ref att id count-res)
  (setq count-res nil)
  (vlax-for blk (vla-get-blocks (vla-get-activedocument (vlax-get-acad-object)))
    ;; 跳过外部参照块
    (if (= (vla-get-isxref blk) :vlax-false)
      (vlax-for ref blk
        (if (= (vla-get-objectname ref) "AcDbBlockReference")
          (progn
            ;; 此处直接复用Lee Mac的属性提取函数,也可替换为你自己的提取逻辑
            (setq id (LM:GetAttributeValue ref attrib-tag))
            (if id
              (if (setq exist (assoc id count-res))
                (setq count-res (subst (cons id (1+ (cdr exist))) exist count-res))
                (setq count-res (cons (cons id 1) count-res))
              )
            )
          )
        )
      )
    )
  )
  count-res
)

3. 批量写入Excel完成自动化

整合GetExcel.lsp的Excel操作函数,实现全流程自动执行:

(defun c:gen-quote ( / excel-path excel-app count-data id row cnt)
  ;; 替换为你实际的Excel模板文件路径
  (setq excel-path "C:\\Users\\xxx\\Desktop\\报价模板.xlsx")
  ;; 打开Excel文件
  (setq excel-app (OpenExcel excel-path))
  ;; 统计块实例数量
  (setq count-data (count-block-by-id "ID"))
  ;; 遍历映射表写入数据
  (foreach map-item *id-row-mapping*
    (setq id (car map-item)
          row (cdr map-item)
          cnt (cond ((assoc id count-data) (cdr (assoc id count-data))) (t 0))
    )
    ;; 示例写入规则:A列写ID,B列写计数,可根据需求修改列号
    (PutCell excel-app row 1 id)
    (PutCell excel-app row 2 cnt)
  )
  ;; 保存并关闭Excel
  (CloseExcel excel-app)
  (princ "报价单生成完成")
  (princ)
)

注意事项

  • 运行前请先提前加载GetExcel.lsp和Lee Mac的块属性提取相关代码片段
  • 如不需要写入计数为0的ID,可在写入前加判断:(if (> cnt 0) 写入逻辑)
  • 建议提前备份原始Excel模板,避免误操作覆盖原有数据
  • 代码中块属性标签、Excel路径、写入列号等参数,需根据你的实际场景修改

内容的提问来源于stack exchange,提问作者Robert

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 21:45:01