Embedding Excel files in your application
Sometimes, you need to include either templates for reports or pre-made Excel files inside your application. The simplest option is just to deploy your xls/x files together with your application, but you might want to embed them in your executable instead.
One way you might think of to include the xls file is using APIMate to "convert" the file into code, then paste that code inside your application. But while that would work, it isn't really a nice solution:
The code generated by APIMate is very repetitive. So for example if you have the cells from A1 to A100 with the numbers 1 to 100, APIMate will write 100 calls to ExcelFile.SetCellValue(1, 1, 1), ExcelFile.SetCellValue(2, 1, 2), and so on, instead of calling ExcelFile.SetCellValue(row, 1, row) in a loop with row from 1 to 100. The idea of APIMate is to show you how to do stuff, so for example you want to know how to format a cell conditionally, you conditionally format it in Excel, then open the file in APIMate and look at the code APIMate generates. But it is not great to actually convert files to code.
For the reason above, the code will be big, resulting in a bigger executable than if you embedded the file directly, and it will be slower to compile too.
Embedded files as resources will normally open faster than the code that APIMate generates uses to create the file. Again, the code generated by APIMate is not designed for this, and it can be inefficient as it sets every cell with a different call.
Resources are simpler to update. Just edit the file in Excel, save it and rebuild your app. While if you used APIMate, you would have to relaunch APIMate and recopy-paste the code every time.
So how do you embed a file as a resource?
In Visual Studio, go to Menu->Project->Add Existing Item... (or press Shift+Alt+A)
In the dialog to select the file set the filter to All Files (*.*) and select the xls/x files you want to embed.
In the solution explorer, right click in the file(s) you added and select "Properties":
- Set the Build Action of the files to Embedded Resource:
- Now, to open the file, use the following code:
Assembly asm = Assembly.GetExecutingAssembly();
using (Stream InStream = asm.GetManifestResourceStream("Resources.test.xlsx"))
{
var xls = new XlsFile(InStream, true);
}
Where the name of the resource is "Namespace.NameOfTheFile" (In this case the namespace is "Resources" so the name of the resource is Resources.test.xlsx)
If you can't figure out the name of the embedded resources, you can use the following method:
static string[] GetEmbeddedFiles()
{
Assembly asm = Assembly.GetExecutingAssembly();
return asm.GetManifestResourceNames();
}
This code will return the names of all embedded files in your executable.