dgn-to-excel
Convert DGN files (v7-v8) to Excel databases. Extract elements, levels, and properties from infrastructure CAD files.
What this skill does
# DGN to Excel Conversion
## Business Case
### Problem Statement
DGN files are common in infrastructure and civil engineering:
- Transportation and highway design
- Bridge and tunnel projects
- Utility networks
- Rail infrastructure
Extracting structured data from DGN files for analysis and reporting can be challenging.
### Solution
Convert DGN files to structured Excel databases, supporting both v7 and v8 formats.
### Business Value
- **Infrastructure support** - Civil engineering focused
- **Legacy format support** - V7 and V8 DGN files
- **Data extraction** - Levels, cells, text, geometry
- **Batch processing** - Process multiple files
- **Structured output** - Excel format for analysis
## Technical Implementation
### CLI Syntax
```bash
DgnExporter.exe <input_dgn>
```
### Supported Versions
| Version | Description |
|---------|-------------|
| V7 DGN | Legacy MicroStation format (pre-V8) |
| V8 DGN | Modern MicroStation format |
| V8i DGN | MicroStation V8i format |
### Output Format
| Output | Description |
|--------|-------------|
| `.xlsx` | Excel database with all elements |
### Examples
```bash
# Basic conversion
DgnExporter.exe "C:\Projects\Bridge.dgn"
# Batch processing
for /R "C:\Infrastructure" %f in (*.dgn) do DgnExporter.exe "%f"
# PowerShell batch
Get-ChildItem "C:\Projects\*.dgn" -Recurse | ForEach-Object {
& "C:\DDC\DgnExporter.exe" $_.FullName
}
```
### Python Integration
```python
import subprocess
import pandas as pd
from pathlib import Path
from typing import List, Optional, Dict, Any
from dataclasses import dataclass
from enum import Enum
class DGNElementType(Enum):
"""DGN element types."""
CELL_HEADER = 2
LINE = 3
LINE_STRING = 4
SHAPE = 6
TEXT_NODE = 7
CURVE = 11
COMPLEX_CHAIN = 12
COMPLEX_SHAPE = 14
ELLIPSE = 15
ARC = 16
TEXT = 17
SURFACE = 18
SOLID = 19
BSPLINE_CURVE = 21
POINT_STRING = 22
DIMENSION = 33
SHARED_CELL = 35
@dataclass
class DGNElement:
"""Represents a DGN element."""
element_id: int
element_type: int
type_name: str
level: int
color: int
weight: int
style: int
# Geometry
range_low_x: Optional[float] = None
range_low_y: Optional[float] = None
range_low_z: Optional[float] = None
range_high_x: Optional[float] = None
range_high_y: Optional[float] = None
range_high_z: Optional[float] = None
# Cell/Text specific
cell_name: Optional[str] = None
text_content: Optional[str] = None
@dataclass
class DGNLevel:
"""Represents a DGN level."""
number: int
name: str
is_displayed: bool
is_frozen: bool
element_count: int
class DGNExporter:
"""DGN to Excel converter using DDC DgnExporter CLI."""
def __init__(self, exporter_path: str = "DgnExporter.exe"):
self.exporter = Path(exporter_path)
if not self.exporter.exists():
raise FileNotFoundError(f"DgnExporter not found: {exporter_path}")
def convert(self, dgn_file: str) -> Path:
"""Convert DGN file to Excel."""
dgn_path = Path(dgn_file)
if not dgn_path.exists():
raise FileNotFoundError(f"DGN file not found: {dgn_file}")
cmd = [str(self.exporter), str(dgn_path)]
result = subprocess.run(cmd, capture_output=True, text=True)
if result.returncode != 0:
raise RuntimeError(f"Export failed: {result.stderr}")
return dgn_path.with_suffix('.xlsx')
def batch_convert(self, folder: str,
include_subfolders: bool = True) -> List[Dict[str, Any]]:
"""Convert all DGN files in folder."""
folder_path = Path(folder)
pattern = "**/*.dgn" if include_subfolders else "*.dgn"
results = []
for dgn_file in folder_path.glob(pattern):
try:
output = self.convert(str(dgn_file))
results.append({
'input': str(dgn_file),
'output': str(output),
'status': 'success'
})
print(f"✓ Converted: {dgn_file.name}")
except Exception as e:
results.append({
'input': str(dgn_file),
'output': None,
'status': 'failed',
'error': str(e)
})
print(f"✗ Failed: {dgn_file.name} - {e}")
return results
def read_elements(self, xlsx_file: str) -> pd.DataFrame:
"""Read converted Excel as DataFrame."""
return pd.read_excel(xlsx_file, sheet_name="Elements")
def get_levels(self, xlsx_file: str) -> pd.DataFrame:
"""Get level summary."""
df = self.read_elements(xlsx_file)
if 'Level' not in df.columns:
raise ValueError("Level column not found")
summary = df.groupby('Level').agg({
'ElementId': 'count'
}).reset_index()
summary.columns = ['Level', 'Element_Count']
return summary.sort_values('Level')
def get_element_types(self, xlsx_file: str) -> pd.DataFrame:
"""Get element type statistics."""
df = self.read_elements(xlsx_file)
type_col = 'ElementType' if 'ElementType' in df.columns else 'Type'
if type_col not in df.columns:
return pd.DataFrame()
summary = df.groupby(type_col).agg({
'ElementId': 'count'
}).reset_index()
summary.columns = ['Element_Type', 'Count']
return summary.sort_values('Count', ascending=False)
def get_cells(self, xlsx_file: str) -> pd.DataFrame:
"""Get cell references (similar to blocks in DWG)."""
df = self.read_elements(xlsx_file)
# Filter to cell elements
cells = df[df['ElementType'].isin([2, 35])] # CELL_HEADER, SHARED_CELL
if cells.empty or 'CellName' not in cells.columns:
return pd.DataFrame(columns=['Cell_Name', 'Count'])
summary = cells.groupby('CellName').agg({
'ElementId': 'count'
}).reset_index()
summary.columns = ['Cell_Name', 'Count']
return summary.sort_values('Count', ascending=False)
def get_text_content(self, xlsx_file: str) -> pd.DataFrame:
"""Extract all text from DGN."""
df = self.read_elements(xlsx_file)
# Filter to text elements
text_types = [7, 17] # TEXT_NODE, TEXT
texts = df[df['ElementType'].isin(text_types)]
if 'TextContent' in texts.columns:
return texts[['ElementId', 'Level', 'TextContent']].copy()
return texts[['ElementId', 'Level']].copy()
def get_statistics(self, xlsx_file: str) -> Dict[str, Any]:
"""Get comprehensive DGN statistics."""
df = self.read_elements(xlsx_file)
stats = {
'total_elements': len(df),
'levels_used': df['Level'].nunique() if 'Level' in df.columns else 0,
'element_types': df['ElementType'].nunique() if 'ElementType' in df.columns else 0
}
# Calculate extents
for coord in ['X', 'Y', 'Z']:
low_col = f'RangeLow{coord}'
high_col = f'RangeHigh{coord}'
if low_col in df.columns and high_col in df.columns:
stats[f'min_{coord.lower()}'] = df[low_col].min()
stats[f'max_{coord.lower()}'] = df[high_col].max()
return stats
class DGNAnalyzer:
"""Advanced DGN analysis for infrastructure projects."""
def __init__(self, exporter: DGNExporter):
self.exporter = exporter
def analyze_infrastructure(self, dgn_file: str) -> Dict[str, Any]:
"""Analyze DGN for infrastructure elements."""
xlsx = self.exporter.convert(dgn_file)
df = self.exporter.read_elements(str(xlsx))
analysis = {
'file': dgn_file,
'statistics': self.exporter.get_statistics(str(xlsx)),
'levels': self.exporter.get_levels(str(xlsx)).to_dict('reRelated in General
modeling-omnistudio-epc-catalog
IncludedSalesforce Industries CME EPC product-modeling skill for Product2-based catalog creation. Use when creating EPC products, configuring product attributes, building offer bundles with Product Child Items, or reviewing EPC DataPack JSON metadata for product catalog changes. TRIGGER when: user creates or updates Product2 EPC records, AttributeAssignment payloads, AttributeMetadata/AttributeDefaultValues, Offer bundles, or ProductChildItem relationships. DO NOT TRIGGER when: designing OmniScripts/FlexCards/Integration Procedures (use building-omnistudio-omniscript, building-omnistudio-flexcard, or building-omnistudio-integration-procedure), implementing Apex business logic (use generating-apex), or troubleshooting deployment pipelines (use deploying-metadata).
relationship-science-coach
IncludedUse this skill for direct, practical adult relationship coaching: couples conflict, repair, trust, marriage, dating, flirting, attachment patterns, emotional connection, sex, desire differences, eroticism, kink negotiation, affection, love languages, breakups, and long-term passion. Draw on Gottman, EFT and Hold Me Tight, attachment science, modern sex research, Perel, Nagoski, Kerner, Schnarch, Love and Stosny, and flexible love-language tools. Be concrete and low-hedge. Redirect only for imminent danger, abuse, coercive control, minors, non-consent, self-harm, stalking, or medical/legal/psychiatric decisions.
building-sf-integrations
IncludedSalesforce integration architecture and runtime plumbing with 120-point scoring. Use this skill to set up Named Credentials, External Credentials, External Services, REST/SOAP callout patterns, Platform Events, and Change Data Capture. TRIGGER when: user sets up Named Credentials, External Services, REST/SOAP callouts, Platform Events, CDC, or touches .namedCredential-meta.xml files. DO NOT TRIGGER when: Connected App/OAuth config (use configuring-connected-apps), Apex-only logic (use generating-apex), or data import/export (use handling-sf-data).
venue-templates
IncludedAccess comprehensive LaTeX templates, formatting requirements, and submission guidelines for major scientific publication venues (Nature, Science, PLOS, IEEE, ACM), academic conferences (NeurIPS, ICML, CVPR, CHI), research posters, and grant proposals (NSF, NIH, DOE, DARPA). This skill should be used when preparing manuscripts for journal submission, conference papers, research posters, or grant proposals and need venue-specific formatting requirements and templates.
let-fate-decide
IncludedDraws the 12 Houses of the Zodiac Tarot spread to inject entropy into planning when prompts are vague, ambiguous, or casually delegated. Interprets the spread to guide next steps. Use when the user says 'let fate decide', 'YOLO', 'whatever', 'idk', or other nonchalant phrases, makes Yu-Gi-Oh references, or when you are about to arbitrarily pick between multiple reasonable approaches. Prefer over ask-questions-if-underspecified when the user's tone is casual or playful rather than precision-seeking.
net-ops
IncludedCross-platform network troubleshooting (Windows, macOS, Linux) via local or remote shell. Use for: DNS broken, can't resolve hostnames, nslookup/dig works but apps fail, NRPT, WFP, scutil, /etc/resolver, systemd-resolved, /etc/resolv.conf, NetworkManager, VPN DNS leak residue (ProtonVPN/Mullvad/WireGuard/AnyConnect), AV/firewall blocking DNS or DoH, Tailscale DNS interaction, intermittent connectivity, remote diagnostics over SSH.