К основному содержанию
скилл CX Codex

excel-to-bim — скилл для Claude Code: что делает и как установить

Скилл excel-to-bim переносит параметры и классификаторы из таблиц Excel обратно в BIM-модели Revit и IFC по идентификаторам элементов. Устраняет ручной ввод данных.

MIT 148 установок ★ 434 обновлён 2026-10-19

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add datadrivenconstruction/DDC_Skills_for_AI_Agents_in_Construction --skill excel-to-bim -a claude-code
Открыть на GitHub

Что делает excel-to-bim

Скилл автоматизирует обратную передачу данных из электронных таблиц в BIM-модели. Он считывает строки Excel через pandas, находит колонку с идентификатором (ElementId, GlobalId или GUID) и сопоставляет свойства со значениями нужного типа: строками, числами или булевыми значениями.

Для Revit инструмент генерирует Python-код под Dynamo, который пакетом назначает параметры элементам через транзакции Revit API. Для открытых моделей скилл формирует обновлённый файл через ifcopenshell. Без установленной библиотеки ifcopenshell прямая обработка IFC завершится ошибкой импорта. Скрипт требует строгого совпадения идентификаторов между таблицей и моделью.

Какие задачи решает

  • обновить параметры элементов Revit из таблицы Excel
  • сгенерировать скрипт Dynamo для пакетного переноса данных в модель
  • сопоставить классификаторы и коды затрат по ElementId или GUID
  • внести изменения из таблицы в свойства модели формата IFC

Примеры запросов агенту

  • Сгенерируй скрипт Dynamo для переноса кодов классификатора из файла costs.xlsx в параметры Revit по колонке ElementId.
  • Сопоставь колонки из таблицы specs.xlsx с текстовыми параметрами модели building.ifc и подготовь обновления.
  • Проверь таблицу elements.xlsx, найди столбец с GlobalId и подготовь список числовых параметров для выгрузки.

Как установить excel-to-bim

1Через Skills CLI (Vercel)

npx skills add datadrivenconstruction/DDC_Skills_for_AI_Agents_in_Construction --skill excel-to-bim -a claude-code

2Вручную: положить файлы

~/.claude/skills/excel-to-bim/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/excel-to-bim/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Вопросы об excel-to-bim

Как установить excel-to-bim в Claude Code?

Выполните команду npx skills add datadrivenconstruction/DDC_Skills_for_AI_Agents_in_Construction --skill excel-to-bim -a claude-code.

Зачем нужен скилл excel-to-bim?

Он исключает ручной перенос атрибутов из Excel обратно в Revit или IFC, автоматически сопоставляя строки таблицы с элементами модели.

Какие зависимости нужны для работы скилла?

Требуется среда Python 3 с библиотекой pandas. Для прямого редактирования файлов формата IFC также обязателен пакет ifcopenshell.

Исходный текст

SKILL.md · MIT
---
name: "excel-to-bim"
description: "Push Excel data back to BIM models. Update parameters, properties, and attributes from structured spreadsheets."
homepage: "https://datadrivenconstruction.io"
metadata: {"openclaw": {"emoji": "📄", "os": ["win32"], "homepage": "https://datadrivenconstruction.io", "requires": {"bins": ["python3"], "anyBins": ["ifcopenshell"]}}}
---
# Excel to BIM Update

## Business Case

### Problem Statement
After extracting BIM data to Excel and enriching it (cost codes, classifications, custom data):
- Changes need to flow back to the BIM model
- Manual re-entry is error-prone
- Updates must match by element ID

### Solution
Push Excel data back to BIM models, updating element parameters and properties from spreadsheet changes.

### Business Value
- **Bi-directional workflow** - BIM → Excel → BIM
- **Bulk updates** - Change thousands of parameters
- **Data enrichment** - Add classifications, codes, costs
- **Consistency** - Spreadsheet as single source of truth

## Technical Implementation

### Workflow
```
BIM Model (Revit/IFC) → Excel Export → Data Enrichment → Excel Update → BIM Model
```

### Python Implementation

```python
import pandas as pd
from pathlib import Path
from typing import Dict, Any, List, Optional, Tuple
from dataclasses import dataclass, field
from enum import Enum
import json


class UpdateType(Enum):
    """Type of BIM parameter update."""
    TEXT = "text"
    NUMBER = "number"
    BOOLEAN = "boolean"
    ELEMENT_ID = "element_id"


@dataclass
class ParameterMapping:
    """Mapping between Excel column and BIM parameter."""
    excel_column: str
    bim_parameter: str
    update_type: UpdateType
    transform: Optional[str] = None  # Optional transformation


@dataclass
class UpdateResult:
    """Result of single element update."""
    element_id: str
    parameters_updated: List[str]
    success: bool
    error: Optional[str] = None


@dataclass
class BatchUpdateResult:
    """Result of batch update operation."""
    total_elements: int
    updated: int
    failed: int
    skipped: int
    results: List[UpdateResult]


class ExcelToBIMUpdater:
    """Update BIM models from Excel data."""

    # Standard ID column names
    ID_COLUMNS = ['ElementId', 'GlobalId', 'GUID', 'Id', 'UniqueId']

    def __init__(self):
        self.mappings: List[ParameterMapping] = []

    def add_mapping(self, excel_col: str, bim_param: str,
                    update_type: UpdateType = UpdateType.TEXT):
        """Add column to parameter mapping."""
        self.mappings.append(ParameterMapping(
            excel_column=excel_col,
            bim_parameter=bim_param,
            update_type=update_type
        ))

    def load_excel(self, file_path: str,
                   sheet_name: str = None) -> pd.DataFrame:
        """Load Excel data for update."""
        if sheet_name:
            return pd.read_excel(file_path, sheet_name=sheet_name)
        return pd.read_excel(file_path)

    def detect_id_column(self, df: pd.DataFrame) -> Optional[str]:
        """Detect element ID column in DataFrame."""
        for col in self.ID_COLUMNS:
            if col in df.columns:
                return col
            # Case-insensitive check
            for df_col in df.columns:
                if df_col.lower() == col.lower():
                    return df_col
        return None

    def prepare_updates(self, df: pd.DataFrame,
                        id_column: str = None) -> List[Dict[str, Any]]:
        """Prepare update instructions from DataFrame."""

        if id_column is None:
            id_column = self.detect_id_column(df)
            if id_column is None:
                raise ValueError("Cannot detect ID column")

        updates = []

        for _, row in df.iterrows():
            element_id = str(row[id_column])

            params = {}
            for mapping in self.mappings:
                if mapping.excel_column in df.columns:
                    value = row[mapping.excel_column]

                    # Convert value based on type
                    if mapping.update_type == UpdateType.NUMBER:
                        value = float(value) if pd.notna(value) else 0
                    elif mapping.update_type == UpdateType.BOOLEAN:
                        value = bool(value) if pd.notna(value) else False
                    elif mapping.update_type == UpdateType.TEXT:
                        value = str(value) if pd.notna(value) else ""

                    params[mapping.bim_parameter] = value

            if params:
                updates.append({
                    'element_id': element_id,
                    'parameters': params
                })

        return updates

    def generate_dynamo_script(self, updates: List[Dict],
                               output_path: str) -> str:
        """Generate Dynamo script for Revit updates."""

        # Generate Python code for Dynamo
        script = '''
# Dynamo Python Script for Revit Parameter Updates
# Generated by DDC Excel-to-BIM

import clr
clr.AddReference('RevitAPI')
clr.AddReference('RevitServices')
from RevitServices.Persistence import DocumentManager
from RevitServices.Transactions import TransactionManager
from Autodesk.Revit.DB import *

doc = DocumentManager.Instance.CurrentDBDocument

# Update data
updates = '''
        script += json.dumps(updates, indent=2)
        script += '''

# Apply updates
TransactionManager.Instance.EnsureInTransaction(doc)

results = []
for update in updates:
    try:
        element_id = int(update['element_id'])
        element = doc.GetElement(ElementId(element_id))

        if element:
            for param_name, value in update['parameters'].items():
                param = element.LookupParameter(param_name)
                if param and not param.IsReadOnly:
                    if isinstance(value, (int, float)):
                        param.Set(float(value))
                    elif isinstance(value, bool):
                        param.Set(1 if value else 0)
                    else:
                        param.Set(str(value))
            results.append({'id': element_id, 'status': 'success'})
        else:
            results.append({'id': element_id, 'status': 'not found'})
    except Exception as e:
        results.append({'id': update['element_id'], 'status': str(e)})

TransactionManager.Instance.TransactionTaskDone()

OUT = results
'''

        with open(output_path, 'w') as f:
            f.write(script)

        return output_path

    def generate_ifc_updates(self, updates: List[Dict],
                             original_ifc: str,
                             output_ifc: str) -> str:
        """Generate updated IFC file (requires IfcOpenShell)."""

        try:
            import ifcopenshell
        except ImportError:
            raise ImportError("IfcOpenShell required for IFC updates")

        ifc = ifcopenshell.open(original_ifc)

        for update in updates:
            guid = update['element_id']

            # Find element by GUID
            element = ifc.by_guid(guid)
            if not element:
                continue

            # Update properties
            for param_name, value in update['parameters'].items():
                # This is simplified - actual IFC property handling is more complex
                # Would need to find/create property sets and properties
                pass

        ifc.write(output_ifc)
        return output_ifc

    def generate_update_report(self, original_df: pd.DataFrame,
                               updates: List[Dict],
                               output_path: str) -> str:
        """Generate report of planned updates."""

        report_data = []
        for update in updates:
            for param, value in update['parameters'].items():
                report_data.append({
                    'element_id': update['element_id'],
                    'parameter': param,
                    'new_value': value
                })

        report_df = pd.DataFrame(report_data)
        report_df.to_excel(output_path, index=False)
        return output_path


class RevitExcelUpdater(ExcelToBIMUpdater):
    """Specialized updater for Revit via ImportExcelToRevit."""

    def __init__(self, tool_path: str = "ImportExcelToRevit.exe"):
        super().__init__()
        self.tool_path = Path(tool_path)

    def update_revit(self, excel_file: str,
                     rvt_file: str,
                     sheet_name: str = "Elements") -> BatchUpdateResult:
        """Update Revit file from Excel using CLI tool."""

        import subprocess

        # This assumes ImportExcelToRevit CLI tool
        cmd = [
            str(self.tool_path),
            rvt_file,
            excel_file,
            sheet_name
        ]

        result = subprocess.run(cmd, capture_output=True, text=True)

        # Parse results (format depends on tool output)
        if result.returncode == 0:
            return BatchUpdateResult(
                total_elements=0,  # Would parse from output
                updated=0,
                failed=0,
                skipped=0,
                results=[]
            )
        else:
            raise RuntimeError(f"Update failed: {result.stderr}")


class DataEnrichmentWorkflow:
    """Complete workflow for data enrichment and update."""

    def __init__(self):
        self.updater = ExcelToBIMUpdater()

    def enrich_and_update(self, original_excel: str,
                          enrichment_excel: str,
                          merge_column: str) -> pd.DataFrame:
        """Merge enrichment data with original export."""

        original = pd.read_excel(original_excel)
        enrichment = pd.read_excel(enrichment_excel)

        # Merge on specified column
        merged = original.merge(enrichment, on=merge_column, how='left',
                                suffixes=('', '_enriched'))

        return merged

    def create_classification_mapping(self, df: pd.DataFrame,
                                      type_column: str,
                                      classification_file: str) -> pd.DataFrame:
        """Map BIM types to classification codes."""

        classifications = pd.read_excel(classification_file)

        # Fuzzy matching could be added here
        merged = df.merge(classifications,
                          left_on=type_column,
                          right_on='type_description',
                          how='left')

        return merged
```

## Quick Start

```python
# Initialize updater
updater = ExcelToBIMUpdater()

# Define mappings
updater.add_mapping('Classification_Code', 'OmniClassCode', UpdateType.TEXT)
updater.add_mapping('Unit_Cost', 'Cost', UpdateType.NUMBER)

# Load enriched Excel
df = updater.load_excel("enriched_model.xlsx")

# Prepare updates
updates = updater.prepare_updates(df)
print(f"Prepared {len(updates)} updates")

# Generate Dynamo script for Revit
updater.generate_dynamo_script(updates, "update_parameters.py")
```

## Common Use Cases

### 1. Add Classification Codes
```python
updater = ExcelToBIMUpdater()
updater.add_mapping('Omniclass', 'OmniClass_Number', UpdateType.TEXT)
updater.add_mapping('Uniclass', 'Uniclass_Code', UpdateType.TEXT)

df = updater.load_excel("classified_elements.xlsx")
updates = updater.prepare_updates(df)
```

### 2. Cost Data Integration
```python
updater.add_mapping('Material_Cost', 'Pset_MaterialCost', UpdateType.NUMBER)
updater.add_mapping('Labor_Cost', 'Pset_LaborCost', UpdateType.NUMBER)
```

### 3. Generate Update Report
```python
report = updater.generate_update_report(df, updates, "planned_updates.xlsx")
```

## Integration with DDC Pipeline

```python
# Full round-trip: Revit → Excel → Enrich → Update → Revit

# 1. Export from Revit
# RvtExporter.exe model.rvt complete

# 2. Enrich in Python/Excel
df = pd.read_excel("model.xlsx")
# Add classifications, costs, etc.
df['OmniClass'] = df['Type Name'].map(classification_dict)
df.to_excel("enriched_model.xlsx")

# 3. Generate update script
updater = ExcelToBIMUpdater()
updater.add_mapping('OmniClass', 'OmniClass_Number')
updates = updater.prepare_updates(df)
updater.generate_dynamo_script(updates, "apply_updates.py")

# 4. Run in Dynamo to update Revit
```

## Resources
- **GitHub**: [DDC Update Revit from Excel](https://github.com/datadrivenconstruction/cad2data-Revit-IFC-DWG-DGN-pipeline-with-conversion-validation-qto/tree/main/DDC_Update_Revit_from_Excel)
- **DDC Book**: Chapter 2.4 - Bidirectional Data Flow

© datadrivenconstruction · MIT · datadrivenconstruction/DDC_Skills_for_AI_Agents_in_Construction

Похожие скиллы

Все скиллы по теме «Данные и базы» →
revit-bim Utopia5327 Плагин revit-bim даёт Claude знание Revit и Dynamo: генерирует готовые Python-скрипты, проверяет модель, ищет коллизии и выгружает IFC по обычному описанию. ★ 11звёзд репо IFC MCP flinker-app Позволяет анализировать BIM-модели в формате IFC, проверять элементы здания, строить отчёты и открывать 3D-просмотрщик прямо из диалога с ассистентом. CX Codex +1 ★ 14звёзд репо Autodesk Revit MCP Server Sam-AEC Сервер связывает ИИ-ассистентов с Autodesk Revit для проверки качества BIM-моделей и правки параметров. Пригодится при аудите проектов и автоматизации рутины проектировщика. CX Codex +1 ★ 125звёзд репо csv-excel-merger OneWave-AI Скилл csv-excel-merger складывает несколько CSV, TSV и Excel в один файл: склеивает, джойнит по ключу, убирает дубли и проверяет арифметику строк. CX Codex +1 1 200установок revit ScanBIM-Labs Подключает модели Revit к ИИ-агенту через Autodesk Platform Services: выгрузка элементов, параметров, спецификаций, поиск коллизий и экспорт в IFC. CX Codex +1 excel-automation daymade Скилл excel-automation для Claude Code создаёт Excel-отчёты через openpyxl, читает сложные xlsm через zipfile и управляет окном приложения на macOS. Автоматизирует финансовые отчёты и перенос бумажных бланков в таблицы. CX Codex +1 1 500установок

Из того же набора156

Весь набор →
xlsx-construction Скилл xlsx-construction для работы с Excel-файлами в строительных проектах: сметы, графики, логи РФИ, ведомости объёмов. Помогает агенту создавать и редактировать таблицы с формулами и форматированием. CX Codex +1 150установок pdf-to-structured Скилл pdf-to-structured парсит таблицы, ведомости материалов и отчёты из PDF в Excel, CSV и JSON. Работает со сканами через OCR и с исходными PDF-файлами через pdfplumber. CX Codex +1 149установок open-construction-estimate Скилл open-construction-estimate для Claude Code сопоставляет элементы BIM со стандартизированными видами работ и помогает рассчитать стоимость по открытым базам расценок. Помогает подготовить строительную смету. CX Codex +1 149установок cwicr-takeoff-helper Скилл cwicr-takeoff-helper для Claude Code, Codex, Cursor и других агентов считает объёмы строительных работ по данным CWICR: площади, объёмы, линейные метры с учётом коэффициентов отходов. CX Codex +1 149установок batch-cad-converter Скилл batch-cad-converter для Claude Code пакетно конвертирует файлы CAD/BIM и отслеживает ход обработки. Запускается по просьбе обработать набор файлов Revit, IFC, DWG или DGN. CX Codex +1 146установок bim-cost-estimation-cwicr Скилл bim-cost-estimation-cwicr для Claude Code оценивает стоимость работ по данным BIM-модели и базе DDC CWICR. Агент подключает его для расчёта сметы по модели Revit или IFC. CX Codex +1 146установок qto-report Скилл qto-report извлекает объёмы, площади и количество элементов из выгрузок BIM и CAD, группирует их и считает сметную стоимость. Пригодится при подготовке ведомостей объёмов работ. CX Codex +1 143установок bim-validation-pipeline Скилл bim-validation-pipeline для Claude Code проверяет IFC-модели на ошибки геометрии, свойств, связей и именования. Сверяет данные модели с требованиями проекта. CX Codex +1 143установок

Спонсоры проекта

Компании, которые помогают держать аналитику открытой