tags:

views:

71

answers:

1

Hey all,

I have a need to copy a worksheet from one workbook into another and I'm a bit stuck. The premise is that I have a "master" workbook that stores the templates for a number of reports and I then need to create a blank copy of a specific worksheet and add it into a new workbook.

This is what I have so far:

private void CreateNewWorkbook(Tables table)
{
    Excel.Application app = null;
    Excel.Workbook book = null;
    Excel.Worksheet sheet = null;

    try
    {
        string startPath = System.IO.Path.GetDirectoryName(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName);
        string filePath = System.IO.Path.Combine(startPath, "sal1011forms.xls");
        Microsoft.Win32.SaveFileDialog sfd = new Microsoft.Win32.SaveFileDialog();

        app = new Excel.Application();
        book = app.Workbooks.Open(filePath);
        sheet = (Excel.Worksheet)book.Worksheets.get_Item((int)table + 1);

        sfd.AddExtension = true;
        sfd.FileName = table.ToString() + ".xls";
        sfd.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

        if (sfd.ShowDialog() == true)
        {
            sheet.SaveAs(sfd.FileName);
        }
    }
    finally
    {
        if (book != null)
        {
            book.Close();
        }
        if (app != null)
        {
            app.Quit();
        }
        this.ReleaseObject(sheet);
        this.ReleaseObject(book);
        this.ReleaseObject(app);
    }
}

The only problem I'm having at the moment is that when I call .Save() on the worksheet, it saves ALL of the worksheets from the original workbook into a new workbook. Any ideas on how to correct this?

Thanks in advance,
Sonny

+1  A: 

You could also use the Sheet.Copy() method.

Basically, Sheet.copy copies the sheet, and will automatically create a new workbook at the same time.

Try adding the following lines to your code, after your call to Worksheets.get_Item:

//Copies sheet and puts the copy into a new workbook
sheet.Copy(Type.Missing, Type.Missing);

//sets the sheet variable to the copied sheet in the new workbook
sheet = app.Workbooks[2].Sheets[1];

Here's the reference for the Copy() function as well: MSDN Link

Slider345