PJW
PJW

Reputation: 5417

Open Copy of Excel Based on Template

I have a WinForms app written in C# that uses the following code to open an Excel Template, prior to exporting data from a SQL database into the Worksheets of the Template.

Microsoft.Office.Interop.Excel.Application oXL = new Microsoft.Office.Interop.Excel.Application();
oXL.Visible = true;
oXL.DisplayAlerts = false;
Microsoft.Office.Interop.Excel.Workbook mWorkBook = oXL.Workbooks.Open(path, 0, false, 5, "", "", false, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "", true, false, 0, true, false, false);
Excel.Worksheet mWorkSheet = mWorkBook.Worksheets["Invoice"];

However, this code actually opens the Template itself, so that any data exported from SQL into the workbook, is saved to the Template. What I want is to programmatically open a copy of the template in the same way this works when you double click a template directly in Windows Explorer and a copy is automatically created, without the original Template being touched.

How can I do this programmatically?

Upvotes: 2

Views: 4300

Answers (2)

KTHan
KTHan

Reputation: 51

You can actually use the Workbooks.Add function of your Excel Application object, and pass in the template path as a parameter. Any future changes that you do programmatically will be done to an as-yet-to-be-saved copy in memory.

I've found that this is useful when you want to prepare / preformat a new excel workbook for a user to interact with later.

string templatePath = "c:\\temp\\template.xlsx";
Workbook wb = oXL.Workbooks.Add(templatePath);
//wb will be a memory copy of template.xlsx

Upvotes: 5

LPH
LPH

Reputation: 1295

then copy the file you want to open to the destination of your choice and open the copy...

System.IO.File.Copy(sourceFile, destFile, true);

the sourcefile is the original file; the destFile is your copy and you open the destfile with oXL.Workbooks.Opeen("path to destfile",....)

So your original file is never touched:)

Upvotes: 3

Related Questions