Content Controls and Repeating Data (or Can I Make a Table?)

The most frequently asked question I receive on Word content controls and databinding goes along the lines of "That's great. No really it is. But you see I've got this list of data and I'd really like to populate a table in Word with it. How do I do that with content controls?". And my answer is "Have I not given you enough already? Be off with you!". Kevin (my boss) told me I had to come up with a better answer...

So here we go (or at least here's the start of it). This is heavily based on the work of Dimitris Koutsanastasis, one of my colleagues in Greece. Essentially, he did the hard work and I copied it. That's pretty much the paradigm for the web isn't it? Some of what Dimitris had done was beyond the scope of what I wanted so I honed his code to produce a simple(r) web page along the lines of the demos I've used in other Open XML nuggets (here, here, here and here).

The problem we're going to tackle goes along the lines of "I have some data like this" (or I can get my data into this sort of format)


and I'd like to produce a Word document that looks something like this:


In other words I have some repeating data of indeterminate length (at design time) and I want to be able to display it in Word using content controls and databinding most likely in a tabular format (a bit like Repeating Sections / Tables in InfoPath).

The key to this is to dynamically generate content controls with the appropriate databindings when you create the document. That does mean some manipulation of the Word reference schema (ie it's a little trickier than just using content controls and your own custom schema) but it turns out it's not too hard. The XPath gets a bit hairy (for me at least) and I found SketchPath to be an invaluable tool in this regard.

Phil Fearon mailed me about SketchPath some weeks ago and I said I'd give it a plug once I'd had the chance to play with it (not that he asked me to plug it!). Now I've used it and I found it to be ideally suited to the task of figuring out the XPath query required to select particular nodes in my document. Just what was needed here and well worth a look. I particularly liked the fact I could do a manual install (assuming I already have .NET Fx 2.0) so all I had to do was copy the .exe and I was good to go.

I'm going to create a nugget or two on this topic in the near future but I thought it was worth at least setting the scene for what's to come...

Technorati Tags: office , open xml