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

查看:325
本文介绍了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.

这是我迄今为止:

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?

谢谢,

桑尼

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



下面是复制()函数的引用,以及:
MSDN链接

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

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