C# - 如何将单个Excel工作表从一个工作簿复制到另一个工作簿? [英] C# - How to copy a single Excel worksheet from one workbook to another?

查看:491
本文介绍了C# - 如何将单个Excel工作表从一个工作簿复制到另一个工作簿?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将工作表从一个工作簿复制到另一个工作表中,我有点困惑。前提是我有一个主工作簿,用于存储多个报告的模板,然后我需要创建一个特定工作表的空白副本并将其添加到新的工作簿中。

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);
    }
}

目前唯一的问题是当我在工作表上调用.Save()时,它将原始工作簿中的所有工作表保存到新的工作簿中。任何关于如何纠正这个问题的想法?

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?

提前感谢,
Sonny

Thanks in advance,
Sonny

推荐答案

您也可以使用Sheet.Copy()方法。

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

基本上,Sheet.copy复制工作表,并将自动在同一时间创建一个新的工作簿。

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

在调用Worksheets.get_Item后,尝试将以下代码添加到代码中:

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];

以下是Copy()函数的参考:
MSDN链接

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

这篇关于C# - 如何将单个Excel工作表从一个工作簿复制到另一个工作簿?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆