Python

Import Text using MicroStation Python

Q How do I import Text Elements using MicroStation Python? I want to read an Excel file that contains text and coordinates, and place the text at each coordinate.

A Here's a small Python program that reads Excel data and creates DGN text elements. It uses Python pandas to read an Excel file of text element coordinates and text content.

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. Import text from Excel to MicroStation, replacing existing text

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

Caveat

This project does little else than existing MicroStation tools such as XYZ Text. However, those tools don't teach you anything about Python, which is the purpose of this article. Going beyond Python, it introduces pandas: the key to reading an Excel file in just a few lines of code.

Python Implementation

The Import 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

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

ImportPointElements

Function ImportPointInfoFromExcel uses pandas to read an Excel file to obtain the list of PointElementInfo.

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 Import Text Elements is available for download.

Folder Structure

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

Usage

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

Download la_solutions_import_text_elements.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.