A few weeks ago, @Michiel Zevenbergen from our Spanish partner GeoTáctica sent me a question:
"When opening the newer Excel files (XLSX) through MapBasic, I need to specify a sheet name. How do I go about this without hardcoding the sheet name in the source code?"
The simple solution is to prompt the user to specify the sheet name. That can be done with a simple Input() function.
Dim sSheetName As String
sSheetName = Input("Sheet Name", "Sheet Name", "Sheet1", "string")
This will show a small dialog to the user where the sheet name can be entered. The default value has been set as Sheet1.
This is a fundamental solution that is easy to implement. It will also work well as long as the sheet names are known to the user or are the same in the Excel files.
A better solution would prompt the user to select a sheet name from a list of existing sheets in the Excel file.
So, how could you make that work?
Again, I found myself walking down the Python path.
The Python module Pandas can be used to work with Excel files. Pandas does, for some work, rely on another Python called openpyxl.
MapInfo Pro comes with Pandas preinstalled. However, you must install the openpyxl module yourself to use it in MapInfo Pro. To do so, launch MapInfo Pro with elevated rights by right-clicking on the shortcut and selecting Run as Administrator.
Now open the Python Console in MapInfo Pro or use the Python type in the SQL Window and execute this command:
This will download and install the module if it isn't already available.
Having Pandas and openpyxl available allows you to quickly get a list of sheets in an Excel file:
It's just a single line of code, but above I wrapped it into a with structure, which ensures the Excel file gets closed afterward.
That's it. The variable sheet_names now holds a list of the sheet names in the Excel file.
All that is left is to prompt the user to initially select the file and then prompt the user to select the sheet to open. And finally, open the Excel file in MapInfo Pro.
------------------------------
Peter Horsbøll Møller
Principal Presales Consultant | Distinguished Engineer
Precisely | Trust in Data
------------------------------