Adding a Chart
Adding a chart proved quite a challenge. There’s a promising-sounding Microsoft Chart COM library, but it turned out not to allow automation in the same way as Word and Excel. Finally we decided to just make up an Excel chart, which is probably easier for users as well. A spreadsheet and chart can be easily designed by hand, and you can update the numbers, recalculate, and save using the tools in Chapter 9. However, the problem remained of how to add a new object and position it correctly within the document. The problem took us several hours to solve and into some dark and surprising corners of Word’s object model. Since the same techniques apply to positioning any OLE object or even a bitmap from a file, it’s worth going over the objects in question.
A little reading of the Word help file turned up the
Shapes
collection, which claims to represent
all the nontext objects in the document: OLE objects, WordArt,
graphic files, text boxes, and Word drawing objects. The collection
has a number of Add methods, including one called
AddOLEObject
. AddOLEObject has a
multitude of arguments, but allows you to specify a class and a file;
thus
Document.Shapes.Add(ClassType='Excel.Chart',FileName='mychart.xls')
inserts the chart somewhere in the document and creates a new
Shape
object to refer to it. The
Shapes collection lives somewhere called the
drawing
layer, which floats
above each page and isn’t part of the document. The
Shape
object has an
Anchor
property that should ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access