| name | dgn-to-excel |
| description | Convert DGN files (v7-v8) to Excel databases. Extract elements, levels, and properties from infrastructure CAD files. |
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
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
DgnExporter.exe "C:\Projects\Bridge.dgn"
for /R "C:\Infrastructure" %f in (*.dgn) do DgnExporter.exe "%f"
Get-ChildItem "C:\Projects\*.dgn" -Recurse | ForEach-Object {
& "C:\DDC\DgnExporter.exe" $_.FullName
}
Python Integration
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
range_low_x: Optional[] =
range_low_y: [] =
range_low_z: [] =
range_high_x: [] =
range_high_y: [] =
range_high_z: [] =
cell_name: [] =
text_content: [] =
:
number:
name:
is_displayed:
is_frozen:
element_count:
:
():
.exporter = Path(exporter_path)
.exporter.exists():
FileNotFoundError()
() -> Path:
dgn_path = Path(dgn_file)
dgn_path.exists():
FileNotFoundError()
cmd = [(.exporter), (dgn_path)]
result = subprocess.run(cmd, capture_output=, text=)
result.returncode != :
RuntimeError()
dgn_path.with_suffix()
() -> [[, ]]:
folder_path = Path(folder)
pattern = include_subfolders
results = []
dgn_file folder_path.glob(pattern):
:
output = .convert((dgn_file))
results.append({
: (dgn_file),
: (output),
:
})
()
Exception e:
results.append({
: (dgn_file),
: ,
: ,
: (e)
})
()
results
() -> pd.DataFrame:
pd.read_excel(xlsx_file, sheet_name=)
() -> pd.DataFrame:
df = .read_elements(xlsx_file)
df.columns:
ValueError()
summary = df.groupby().agg({
:
}).reset_index()
summary.columns = [, ]
summary.sort_values()
() -> pd.DataFrame:
df = .read_elements(xlsx_file)
type_col = df.columns
type_col df.columns:
pd.DataFrame()
summary = df.groupby(type_col).agg({
:
}).reset_index()
summary.columns = [, ]
summary.sort_values(, ascending=)
() -> pd.DataFrame:
df = .read_elements(xlsx_file)
cells = df[df[].isin([, ])]
cells.empty cells.columns:
pd.DataFrame(columns=[, ])
summary = cells.groupby().agg({
:
}).reset_index()
summary.columns = [, ]
summary.sort_values(, ascending=)
() -> pd.DataFrame:
df = .read_elements(xlsx_file)
text_types = [, ]
texts = df[df[].isin(text_types)]
texts.columns:
texts[[, , ]].copy()
texts[[, ]].copy()
() -> [, ]:
df = .read_elements(xlsx_file)
stats = {
: (df),
: df[].nunique() df.columns ,
: df[].nunique() df.columns
}
coord [, , ]:
low_col =
high_col =
low_col df.columns high_col df.columns:
stats[] = df[low_col].()
stats[] = df[high_col].()
stats
:
():
.exporter = exporter
() -> [, ]:
xlsx = .exporter.convert(dgn_file)
df = .exporter.read_elements((xlsx))
analysis = {
: dgn_file,
: .exporter.get_statistics((xlsx)),
: .exporter.get_levels((xlsx)).to_dict(),
: .exporter.get_element_types((xlsx)).to_dict(),
: .exporter.get_cells((xlsx)).to_dict()
}
df.columns:
lines = df[df[].isin([, , , ])].shape[]
analysis[] = lines
complex_elements = df[df[].isin([, , , ])].shape[]
analysis[] = complex_elements
annotations = df[df[].isin([, , ])].shape[]
analysis[] = annotations
analysis
() -> [, ]:
xlsx1 = .exporter.convert(dgn1)
xlsx2 = .exporter.convert(dgn2)
df1 = .exporter.read_elements((xlsx1))
df2 = .exporter.read_elements((xlsx2))
levels1 = (df1[].unique()) df1.columns ()
levels2 = (df2[].unique()) df2.columns ()
{
: dgn1,
: dgn2,
: (df2) - (df1),
: (levels2 - levels1),
: (levels1 - levels2),
: (levels1 & levels2)
}
() -> pd.DataFrame:
df = .exporter.read_elements(xlsx_file)
coord_cols = [, , ]
col [, , ,
, , ,
, , ]:
col df.columns:
coord_cols.append(col)
df[coord_cols].copy()
:
():
.exporter = exporter
() -> [, ]:
df = .exporter.read_elements(xlsx_file)
df.columns:
{}
level_map = {}
level df[].unique():
level_map[(level)] =
level_map
() -> pd.DataFrame:
df = .exporter.read_elements(xlsx_file)
df[df[].isin(levels)]
() -> pd.DataFrame:
df = .exporter.read_elements(xlsx_file)
df.columns df.columns:
pd.DataFrame()
report = pd.crosstab(df[], df[], margins=)
report
() -> :
exporter = DGNExporter(exporter_path)
output = exporter.convert(dgn_file)
(output)
() -> [, ]:
exporter = DGNExporter(exporter_path)
analyzer = DGNAnalyzer(exporter)
analyzer.analyze_infrastructure(dgn_file)
Output Structure
Excel Sheets
| Sheet | Content |
|---|
| Elements | All DGN elements with properties |
| Levels | Level definitions |
| Cells | Cell library |
Element Columns
| Column | Type | Description |
|---|
| ElementId | int | Unique element ID |
| ElementType | int | Type code (3=Line, 17=Text, etc.) |
| Level | int | Level number |
| Color | int | Color index |
| Weight | int | Line weight |
| Style | int | Line style |
| RangeLowX/Y/Z | float | Bounding box minimum |
| RangeHighX/Y/Z | float | Bounding box maximum |
| CellName | string | Cell name (for cell elements) |
| TextContent | string | Text content (for text elements) |
Quick Start
exporter = DGNExporter("C:/DDC/DgnExporter.exe")
xlsx = exporter.convert("C:/Projects/Highway.dgn")
print(f"Output: {xlsx}")
df = exporter.read_elements(str(xlsx))
print(f"Total elements: {len(df)}")
levels = exporter.get_levels(str(xlsx))
print(levels)
types = exporter.get_element_types(str(xlsx))
print(types)
Common Use Cases
1. Infrastructure Analysis
exporter = DGNExporter()
analyzer = DGNAnalyzer(exporter)
analysis = analyzer.analyze_infrastructure("highway.dgn")
print(f"Total elements: {analysis['statistics']['total_elements']}")
print(f"Linear elements: {analysis['linear_elements']}")
print(f"Annotations: {analysis['annotations']}")
2. Level Audit
exporter = DGNExporter()
xlsx = exporter.convert("bridge.dgn")
levels = exporter.get_levels(str(xlsx))
for idx, row in levels.iterrows():
print(f"Level {row['Level']}: {row['Element_Count']} elements")
3. GIS Integration
analyzer = DGNAnalyzer(exporter)
xlsx = exporter.convert("utilities.dgn")
coords = analyzer.extract_coordinates(str(xlsx))
coords.to_csv("coordinates.csv", index=False)
4. Revision Comparison
analyzer = DGNAnalyzer(exporter)
diff = analyzer.compare_revisions("rev1.dgn", "rev2.dgn")
print(f"Elements changed: {diff['element_count_diff']}")
Integration with DDC Pipeline
from dgn_exporter import DGNExporter, DGNAnalyzer
exporter = DGNExporter("C:/DDC/DgnExporter.exe")
xlsx = exporter.convert("highway_project.dgn")
stats = exporter.get_statistics(str(xlsx))
print(f"Elements: {stats['total_elements']}")
print(f"Levels: {stats['levels_used']}")
analyzer = DGNAnalyzer(exporter)
coords = analyzer.extract_coordinates(str(xlsx))
coords.to_csv("for_gis.csv", index=False)
Best Practices
- Check version - V7 and V8 have different capabilities
- Reference files - Process all reference files separately
- Level mapping - Document level standards for your organization
- Coordinate systems - Verify units and coordinate systems
- Cell libraries - Export cells separately if needed
Resources
- GitHub: cad2data Pipeline
- DDC Book: Chapter 2.4 - CAD Data Extraction
- MicroStation: Infrastructure-focused CAD software