在所有其他人之后添加一个新的工作表

在所有其他人之后添加一个新的工作表

本文介绍了Excel Interop - 在所有其他人之后添加一个新的工作表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试向Excel工作簿添加一个新的工作表,并将其作为C#Excel Interop中的最后一个工作表。



看起来很简单,我以为下面的代码会这样做:

  c> c 添加和之后的参数传递给我的最后一个工作表的名称。 code>移动方法,没有快乐!



这是我试过的,所以我的问题是如何添加工作表到Excel工作簿,并将其作为工作簿中的最后一张表使用C#Excel Interop?



谢谢

解决方案

在这里查看文档,它表示after对象不是数字位置;表示您要将您的工作表定位的工作表的对象。代码应该是(未经测试的):

  workbook.Sheets.Add(After:workbook.Sheets [workbook.Sheets 。计数]); 


I am trying to add a new worksheet to an Excel workbook and make this the last worksheet in the book in C# Excel Interop.

It seems really simple, and I thought the below code would do it:

using System.Runtime.InteropServices;
using Excel = Microsoft.Office.Interop.Excel;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            var excel = new Excel.Application();

            var workbook = excel.Workbooks.Open(@"C:\test\Test.xlsx");
            workbook.Sheets.Add(After: workbook.Sheets.Count);

            workbook.Save();
            workbook.Close();

            Marshal.ReleaseComObject(excel);
        }
    }
}

No such luck. I get this helpful error:

I found this page on Microsoft.com which suggested I try and add the sheet first and then move it so I tried that as shown below. I know that this webpage targets Excel 95 but the VBA is still there to use so I was hoping it would still work:

using System.Runtime.InteropServices;
using Excel = Microsoft.Office.Interop.Excel;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            var excel = new Excel.Application();

            var workbook = excel.Workbooks.Open(@"C:\test\Test.xlsx");
            workbook.Sheets.Add();
            workbook.Sheets.Move(After: workbook.Sheets.Count);

            workbook.Save();
            workbook.Close();

            Marshal.ReleaseComObject(excel);
        }
    }
}

I get the same error as above. I have also tried passing the name of my last worksheet as a string as the After parameter in both the Add and Move methods, no joy!

That is what I have tried, so my question is how do I add a worksheet to an Excel workbook and make this the last sheet in the workbook using C# Excel Interop?

Thanks

解决方案

Looking at the documentation here http://msdn.microsoft.com/en-us/library/microsoft.office.tools.excel.worksheet.move(v=vs.80).aspx, it indicates that the 'after' object isn't a numerical position; it's the object representing the sheet you want to position your sheet after. The code should probably be something like (untested):

workbook.Sheets.Add(After: workbook.Sheets[workbook.Sheets.Count]);

这篇关于Excel Interop - 在所有其他人之后添加一个新的工作表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 01:34