简体   繁体   English

在Excel加载项(C#)中以编程方式创建工作表

[英]Programmatically creating worksheets in an Excel Add In (C#)

According to MSDN, one can programmatically create and delete Excel Worksheets in Visual Studio ( http://msdn.microsoft.com/en-us/library/6fczc37s.aspx ). 根据MSDN,可以在Visual Studio( http://msdn.microsoft.com/zh-cn/library/6fczc37s.aspx )中以编程方式创建和删除Excel工作表。 The code to do so is as follows: 这样做的代码如下:

private void createNewAccount()
{            
    Excel.Worksheet newWorksheet;
    newWorksheet = Globals.ThisAddIn.Application.ThisWorkbook.Worksheets.Add();            
}

One of the forms in my project has a button carrying this code. 我的项目中的一个表单有一个带有此代码的按钮。 The user is supposed to be able to press it and create a new worksheet, but it doesn't work. 用户应该可以按它并创建一个新的工作表,但是它不起作用。 So I decided to make it a button on a ribbon tab, instead. 因此,我决定将其设置为功能区选项卡上的按钮。 That didn't work either. 那也不起作用。 What am I missing? 我想念什么?

My answer is not going to be too long. 我的回答不会太长。

If you need to go Microsoft way, please first be sure to first create a Book. 如果您需要采用Microsoft方式,请首先确保首先创建一本Book。 Remember Excel files resemble a workbook , then, inside, you can create worksheets. 记住Excel文件类似于工作簿 ,然后在内部可以创建工作表。

If you don't please take a look at NPOI project . 如果您不愿意,请看一下NPOI项目

With both approaches you will have to create the workbook, then the worksheets inside. 使用这两种方法,您将必须先创建工作簿,然后再创建工作表。

More on this link . 有关此链接的更多信息

Well, If you are sure you have access to a WorkBook I would recommend you to: 好吧,如果您确定可以访问工作簿,则建议您:

1.- Use the parameters of the WorkSheets.Add method 1.-使用WorkSheets.Add方法的参数

2.- Please take a look at this example . 2.-请看一下这个例子

3.- Persist the workbook after the worksheet is added. 3.-在添加工作表后坚持工作簿。 This will allow to check if it was added or not. 这将允许检查它是否被添加。

Last but not least, debug, debug and debug. 最后但并非最不重要的一点是调试,调试和调试。

Hope that helps, 希望能有所帮助,

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM