PJW PJW - 1 year ago 99
C# Question

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?

Answer Source

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:)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download