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.
We occasionally read a post on Be Communities: MicroStation Forum about round-tripping text between MicroStation and Excel. By 'round-tripping' we mean …
You can use Python projects Export Text and Replace Text as the foundation of such a round-tripping application.
Going beyond Python, this project introduces pandas: the key to reading an Excel file in just a few lines of code.
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 …
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.
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.
There's a description of our Python project folder structure.
Replace Text Elements is intended to be run from MicroStation's Python Manager.
Unpack the ZIP file and copy the Python file into a folder that MicroStation knows about.
Use MicroStation's Python Manager to find and execute the script.
Post questions about MicroStation programming to the MicroStation Programming Forum.