Fun and games with SharePoint and Open XML

I’m starting to work on a SharePoint project right now that sounds like it should be simple, but is actually kind of complicated. Or at least if seems to me like it is, possibly because I’m still new to SharePoint and I’m not always stumbling across the “right” way to solve the various problems I’m encountering.

The basic problem is to take a purchase requisition, stored as a normal SharePoint list item, and allow the user to save it to a nicely-formatted Word document or PDF, so that it can be sent out to a vendor as a purchase order.

I went through quite a few ideas for this, most of which are likely very wrong. What I’ve settled on, for now, is creating a new ASP.NET application page which will take the ID of the purchase requisition on the query string. I can then link to this page through a custom action on the regular list item display/edit form. The new page will read the fields of the list item via the SharePoint object model, substitute them into a Word document template, then allow the end-user to download that document from their browser.

Previously, I’ve always used third-party libraries, such as EPPlus, to generate Word and Excel files. But, in this case, I wanted to avoid third-party DLLs and see if I could do what I needed with just the Open XML SDK.

I’m discovering a lot of interesting things about Open XML as I go. First, there’s a tool in the Open XML SDK, called the “Productivity Tool”, that can take a Word document and generate the C# code necessary to create that Word document from scratch. When I started working on this project, I was concerned about where I would store the document template; now, it turns out that I don’t have to store it at all! I can just generate it from scratch in code each time. And I can just modify the generated code a bit so that the values I need to substitute in can be variables instead of constants.

The generated code, unfortunately, is pretty messy. My first shot at running my purchase order template through the tool resulted in 10,000 lines of code. I made some changes in the document to simplify things, and I got down to about 7500 lines, which is still a lot.

I also discovered the “Power Tools for Open XML” library, which can be used to simplify the formatting on a Word document a bit. I ran it on my template, then generated new C# code, and now I’m down to 7200 lines. Still a lot, but it’s manageable.

So it seems like I now have a viable solution that doesn’t need to read or write anything to/from the file system, doesn’t have any oddball DLL dependencies, and should be pretty straightforward to code, test, and deploy.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.