OdeToCode IC Logo

Easily Generate Microsoft Office Files From C#

Wednesday, July 30, 2014

It was over a decade ago when I was first asked to generate Microsoft Office files from a web application. In those days there weren’t many options available to create Office files, but for small applications it was possible to automate Office programs on the server with COM. Since Office wasn’t designed to run on a server, the automation approach always felt like climbing a frozen waterfall. From a support page:

Microsoft does not currently recommend, and does not support, automation of Microsoft Office applications from any unattended, non-interactive client application or component … because Office may exhibit unstable behavior and/or deadlock when Office is run in this environment.

These days, Office files are no longer in a proprietary binary format, and are we can create the files directly without using COM automation. A .docx Word file, for example, is a collection of XML documents zipped into a single file. The official name of the format is Open XML.

There is an SDK to help with reading and writing OpenXML, and a Productivity Tool that can generate C# code for a given file. All you need to do is load a document, presentation, or workbook into the tool and press the “Reflect Code” button.

 

Document Reflector

The downside to this tool is that even a simple document will generate 4,000 lines of code. Another downside is that the generated code assumes it will write directly to the file system, however it is easy to pass in an abstract Stream object instead.

So while this code isn’t perfect, the code does produce valid document and  is useful for figuring out how the SDK classes work together. It’s also not difficult to rework the logic so the class functions as a “view”. You can pass in a model object and have the code dynamically generate a document by replacing hard coded content inside with data from the model.