How can I load excel in visio using python?

50 Views Asked by At

I have an excel file containing columns: Process step ID, Process step description, Next step ID, Connector label, Shape type, Function, Phase.

It has everything required. I want to load it in visio and map the columns to corresponding types and then generate flow. I can do it manually using opening visio-> data tab-> etc.

I want to automate the process using python and (win32com or comtypes). But I am getting so many errors.

Here is the initial code I have been trying so far:

import comtypes.client
import pywintypes

def create_visio_diagram(excel_file, process_id_col, description_col):
    visio_app = comtypes.client.CreateObject("Visio.Application")
    visio_app.Visible = True  # Set to False if you don't want to see Visio GUI

    # Create a new document using a generic empty template
    doc = visio_app.Documents.Add("Blank Drawing.vst")

    # Access the active page
    page = doc.Pages.Item(1)

    # Link the data from Excel to shapes on the page
    try:
        dataRecordset = page.DataRecordsets.Add("DataRecordset")
        dataRecordset.GetRecordset(excel_file, 0, 1, "Sheet1")
        dataRecordset.SetDataRowLinkedColumn("Process ID", process_id_col)
        dataRecordset.SetDataRowLinkedColumn("Description", description_col)
        dataRecordset.Refresh()
    except pywintypes.com_error as e:
        print(f"Error linking data: {e}")

    # Save the document
    doc.SaveAs("C:\\Path\\To\\Your\\Output\\File.vsdx")

    # Close Visio
    visio_app.Quit()

# Example usage
excel_file_path = "C:\\Path\\To\\Your\\Excel\\Workbook.xlsx"
process_id_column = "process_id"
description_column = "description"

create_visio_diagram(excel_file_path, process_id_column, description_column)
1

There are 1 best solutions below

0
Nikolay On

There is no API in Visio to create diagram (flow) from data as of now. This is possible only manually.