Reading and writing to Excel 2007 or Excel 2010 from C# - Part III: Shared Strings

[Note: See the series index for a list of all parts in this series.]

[Image of Linq-to-XML connected to System.IO.Packaging]

Excel’s file format is interesting when compared to the rest of the Office Suite because it can store data in two places—where most others store it in a single place. The reason for this dual approach is performance optimization while keeping the file size small. For example, let’s consider a scenario with a single sheet containing some data:

[Excel table example]

If each cell is processed individually, the total size would be 32 characters of data. However, with a shared strings model, the result looks like this:

[Adjusted table]

The output remains the same, but values are processed only once, reducing the size—in this case, to 24 characters.

The Excel format is flexible: it allows either method. Note that the Excel client always uses shared strings, so for reading, you should support it. This raises an interesting question: what happens if you fill a spreadsheet via direct input and then open it in Excel? Well, Excel detects the structure, remaps it automatically, and—regardless of whether changes were made—prompts the user to save the file when they try to close it. The element we loaded at the end of...