Data panel

Blocks to Excel

Exports block references to an Excel workbook: one row per block with its handle, layer, position, rotation and scale, and one column per attribute tag.

On the ribbonButton, Data panel
NeedsAn open drawing; optionally a selection
CommandPYBLOCKSTOEXCEL
AliasBX
ShortcutNone set (bind one in Shortcuts)

What it does#

Writes one row per block reference to a new .xlsx workbook, on a sheet called Blocks. With block references selected it exports just those; with nothing selected it exports every block reference in model space and on every layout. The workbook is made to be edited and read back by Excel to Blocks, which matches rows to blocks by their handle. The command is PYBLOCKSTOEXCEL.

The columns, in this order:

  • Handle: the reference's handle, which identifies it in this drawing.
  • Block: the block name. A dynamic block reports its definition's real name, not the anonymous *U copy AutoCAD makes.
  • Layer, and Space: Model or the layout's name.
  • X, Y, Z: the insertion point.
  • Rotation in degrees, 0 up to 360.
  • Scale: one number when the X, Y and Z scales are equal, else x, y, z as text.
  • Then one column per attribute tag found on any exported block, in the order the drawing holds them. Tags that differ only in case share a column. A block without that tag has an empty cell.

Rows are sorted by block name, then by handle. The header row is bold.

How to use it#

  1. Select the block references to export, or clear the selection to export the whole drawing.
  2. Click Blocks to Excel (or type PYBLOCKSTOEXCEL).
  3. Pick where to save. The suggested name is drawing - Blocks.xlsx beside the drawing (Drawing - Blocks.xlsx for a drawing never saved). Choosing an existing file replaces it.
  4. A toast says how many references were exported, and where.

Good to know / limits#

  • Only references placed directly in model space or on a layout are exported. Blocks nested inside other blocks are not.
  • Xref attachments are never included, even when selected.
  • A selection with no block references in it exports nothing, and the toast says to clear the selection to export the whole drawing.
  • If the file is open in Excel, Windows will not let it be replaced: the tool says so. Close it and run again.
  • Constant attributes (fixed in the block definition) are not stored on the reference, so they do not appear. A block with two attributes of the same tag shows only one value.
  • Handles belong to one drawing. The workbook is for reading back into the drawing it came from, or a Save As copy of it.

Other uses#

  • A quick register of equipment tags, door numbers or title block fields, without setting up a data extraction.
  • Check positions and rotations at a glance: sort the X column, filter on a layer, look for a scale that is not 1.
  • Hand a list of tagged items to someone who does not have AutoCAD.

Source#

The tool's own files, word for word as shipped in Data.panel/Blocks_to_Excel.pushbutton. Every pyACAD tool is an ordinary bundle: copy these into your own extension and change what you like.

script.py Runs on a click. View on GitHub
# -*- coding: utf-8 -*-
"""Exports block references to an Excel workbook, one row per reference.

The selected block references when there are any, else every one in model space
and the layouts. Columns: Handle, Block, Layer, Space, X, Y, Z, Rotation (degrees),
Scale, then one column per attribute tag found on any of them. Edit attribute
values or layers in Excel and Excel to Blocks writes them back, matched by Handle.
"""

import os

from pyacad import blocks, forms, script, sel, toast, xl

__title__ = 'Blocks to Excel'

TITLE = 'Blocks to Excel'
XLSX = 'Excel workbook (*.xlsx)|*.xlsx'


def plural(count, word):
    return '%d %s%s' % (count, word, '' if count == 1 else 's')


def default_path(drawing, what):
    """'<drawing> - <what>.xlsx' beside the drawing; just the name when unsaved."""
    if not drawing or drawing == 'untitled':
        return 'Drawing - %s.xlsx' % what
    folder, name = os.path.split(drawing)
    return os.path.join(folder, '%s - %s.xlsx' % (os.path.splitext(name)[0], what))


def write_workbook(path, headers, rows, sheet):
    """Writes a fresh workbook; True when it worked. The Save dialog already
    asked before replacing a file, so an old one is removed rather than merged."""
    try:
        if os.path.exists(path):
            os.remove(path)
        xl.write(path, rows, headers=headers, sheet=sheet)
    except (IOError, OSError) as error:
        toast.error('Could not write the workbook', 'Is it open in Excel? %s' % error)
        return False
    return True


def run():
    drawing = script.get_document_path()
    if drawing is None:
        toast.warning('No drawing is open', 'Open a drawing, then run %s' % TITLE)
        return

    picked = sel.current()
    refs = blocks.snapshots(picked if picked else None)
    if not refs:
        if picked:
            toast.info('No block references in the selection',
                       'Clear the selection to export the whole drawing')
        else:
            toast.info('No block references in this drawing')
        return

    path = forms.save_file(XLSX, default_path(drawing, 'Blocks'), 'Export blocks to Excel')
    if not path:
        return                                          # cancelled: say nothing

    headers, rows = blocks.export_rows(refs)
    if write_workbook(path, headers, rows, 'Blocks'):
        scope = 'selected ' if picked else ''
        toast.success('Exported %s' % plural(len(rows), scope + 'block reference'), path)


if '__commandpath__' in globals():
    run()
bundle.yaml The bundle contract: the keys pyACAD reads for this tool. View on GitHub
title: Blocks to Excel
tooltip: Exports every block reference in the drawing, or just the selected ones, to an Excel workbook. One row per block with its handle, layer, position, rotation and scale, and one column per attribute tag.
context: doc
keytip: DB
alias: BX