crookie
crookie

Reputation: 260

Open Excel Template from C# Resource

I know similar questons have been asked before but cannot find the exact answer I am looking for.

I have an Excel file that I want to use for reporting puropses and populate with lots of results. So I was planning to have an Excel template file as a resource, open it then populate it but it to be left as an unsaved "Book1" workbook. Everything I am reading seems to talk about saving a copy of the resorce file somewhere on the physical disk, but i didn't really want to do this, as I want to leave it up to the user to decide where to save it.

Can someone please help me?

Upvotes: 1

Views: 3576

Answers (3)

Darien shannon
Darien shannon

Reputation: 61

This should help you out. (tested in .NET 4.5).

public void openExcelTemplateFromResources ()
{
    string tempPath = System.IO.Path.GetTempFileName(); 

    System.IO.File.WriteAllBytes(tempPath, Properties.Resources.excelResource);

    Excel.Application excelApplication = new Excel.Application();
    Excel._Workbook excelWorkbook;
    excelWorkbook = excelApplication.Workbooks.Open(tempPath)

    excelApplication.Visible = true; // at this point its up to the user to save the file
}

Upvotes: 2

Sorceri
Sorceri

Reputation: 8033

You can add it as a resource and extract it into a stream using the following example. < Namespace > is the namespace of your app, and < FileName > is the actual name of the file. This will allow you to prompt the user for the save location and then write the stream to disk.

Stream stream = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("<Namespace>.Resources.<FileName>")

Upvotes: 0

BendEg
BendEg

Reputation: 21108

I would recommend that you save a temporary version of the file in the user AppData\Local\ directory. Because in this folder you have always read and write access. After your report is created, you can show a save dialog to decide where to copy your excel-file.

To be sure you use the correct folder, try to use this:

Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + "\\YourFolder";

Waht do you mean with Resource? Do you want to store your report in an assembly?

Upvotes: 0

Related Questions