Using C# To Draw An OrgChart in Visio 2010
Friday, May 31, 2013 at 8:12AM I added a new sample to my NuGet package Visio C# Samples. It's a very straightforward sample of how to draw an org chart.
Some of the things it demonstrates
- How to open a template-based visio document (such as an org chart)
- Using the DropManyU API
- Using the AutoConnect API
- How to detect which version of Visio is being used
Notes:
- The code works for both VIsio 2010 and Visio 2013.
- Auto-positioning of the shapes is NOT covered. That is a separate problem I didn't want to cover in this example.
The code is shown below:
var app = new IVisio.ApplicationClass();
var docs = app.Documents;
// Create a new OrgChart using the org chart template
var doc = docs.AddEx("orgch_u.vst", IVisio.VisMeasurementSystem.visMSUS, 0,0);
var page = app.ActivePage;
// Get the masters
bool is_visio_2013 = app.Version.StartsWith("15.");
var orgchart_masters = doc.Masters;
var position_master = orgchart_masters[is_visio_2013 ? "Position Belt" : "Position"];
var dyncon = orgchart_masters["Dynamic Connector"];
// three masters to drop
var masters = new object[] { position_master, position_master, position_master };
// three coordinates to make the drop
var xy_array = new double[] {1,2 ,3,5, 6,2};
// perform the drop of all shapes at once
// and get the shape ids back out
System.Array shape_ids_sa;
page.DropManyU(masters, xy_array, out shape_ids_sa);
var shape_ids = (short[])shape_ids_sa;
// using the shape ids, get the shape objects
var shape0 = page.Shapes.ItemFromID16[shape_ids[0]];
var shape1 = page.Shapes.ItemFromID16[shape_ids[1]];
var shape2 = page.Shapes.ItemFromID16[shape_ids[2]];
// perform connections using the Dynamic Connection master
shape0.AutoConnect(shape1, IVisio.VisAutoConnectDir.visAutoConnectDirNone, dyncon);
shape1.AutoConnect(shape2, IVisio.VisAutoConnectDir.visAutoConnectDirNone, dyncon);