问题
According to MSDN, one can programmatically create and delete Excel Worksheets in Visual Studio (http://msdn.microsoft.com/en-us/library/6fczc37s.aspx). 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?
回答1:
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. Remember Excel files resemble a workbook, then, inside, you can create worksheets.
If you don't please take a look at NPOI project.
With both approaches you will have to create the workbook, then the worksheets inside.
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
2.- Please take a look at this example.
3.- Persist the workbook after the worksheet is added. This will allow to check if it was added or not.
Last but not least, debug, debug and debug.
Hope that helps,
来源:https://stackoverflow.com/questions/22466252/programmatically-creating-worksheets-in-an-excel-add-in-c