Python

Replace Text using MicroStation Python

Q How do I replace Text Elements using MicroStation Python? I want to read an Excel file that contains element IDs and text, and replace the text having each ID.

A Here's a small Python program that reads Excel data and replaces DGN text elements. It uses Python pandas to read an Excel file of text element IDs and text content. The Excel file should contain the Element ID of each text element to be updated. You can create an Excel file of text that includes Element IDs using the Text Exporter.

Text Round-Trip

We occasionally read a post on Be Communities: MicroStation Forum about round-tripping text between MicroStation and Excel. By 'round-tripping' we mean …

  1. Export text from a MicroStation DGN file to Excel
  2. Modify the text in Excel
  3. Read text from Excel replacing existing DGN text using the code described here

You can use Python projects Export Text and Replace Text as the foundation of such a round-tripping application.

Caveat

Going beyond Python, this project introduces pandas: the key to reading an Excel file in just a few lines of code.

Python Implementation

The Replace Text Elements example borrows from Python articles and examples delivered with MicroStation Python.

We build a list of point data from an Excel file. The Excel file should contain a worksheet something like this …

DGN text Imported from Excel

Element ID

The Excel data must include the Element ID of each element you want to update, and its text replacement. The coordinate data is not used, because we modify an existing text element.

This project, and some others, make use of a PointElementInfo class. It's described here.

ImportPointElements

Function ReplacePointInfoFromExcel uses pandas to read an Excel file to obtain the list of PointElementInfo. It ignores any row that has an Element ID of zero.

We need a file name to create the Imported data. GetTableInputFolder() is provided by la_solutions.configuration_vars. In this example, the Excel file is hard-coded …

    from la_solutions.configuration_vars import GetTableInputFolder
    _, folder = GetTableInputFolder()
    excelFile = os.path.join(os.path.dirname(os.path.abspath(folder)), EXCEL_TEST_FILE)

Here's the essence of using pandas to read an Excel file …

    with pd.ExcelFile(excelFile) as reader:
    	frame = pd.read_excel(reader, "sheet01")

The Python source code of Replace Text Elements is available for download.

Folder Structure

There's a description of our Python project folder structure.

Usage

Replace Text Elements is intended to be run from MicroStation's Python Manager.

Download la_solutions_replace_text_elements_from_Excel.zip

Unpack the ZIP file and copy the Python file into a folder that MicroStation knows about.

Python Manager

Use MicroStation's Python Manager to find and execute the script.

Questions

Post questions about MicroStation programming to the MicroStation Programming Forum.