Search code examples
c#.netoffice-interopexcel-interoptemporary-files

Cleanest approach to using an Excel file as a template for exporting


I have a (winforms) project which allows users to export to an Excel spreadsheet. This exporting is done via the interop (Microsoft.Office.Interop.Excel) and works off a "template" spreadsheet I have created. The template should remain unchanged during the export as the code programmatically saves to a different file path. I want to know what the cleanest approach to this is.

At the moment I have added the template spreadsheet as a file to my project. My understanding is that if I set it's Build Action property to Embedded Resource, I would still need to at least save the file to the user's hard drive at least temporarily in order for the interop to access it. My understanding is that the interop automates an Excel process to open the file. So is it advisable to copy my template out of the embedded resources into the user's temp folder each time they try and export and work from there (i.e. using System.IO.Path.GetTempFileName())? If so, then how do I actually get hold of the embedded resource? I tried looking for it in Properties.Resources but it is not there. Or is there a smarter way to go about this?


Solution

  • Look at the following link, which explains how to save the embedded ressource to file: https://stackoverflow.com/a/864276/342594

    As a side note: I would store the file somewhere in the user's folder (e.g. My Documents). Then you could give the user the opportunity to alter the template. You could then first check if the template exists and create it if not. Otherwise use the existing template. If the user broke the template your export method would probably notice it and you could give the user the opportunity to revert to the original template.