简体   繁体   中英

How to insert existing worksheet in Excel using C#?

I am trying to insert an existing sheet from Excel into my current worksheet. But, instead to inserting into my current worksheet, it creates new worksheet. What am I missing in my code?

I am using this:

Workbook wkActive = Globals.ThisAddIn.Application.ActiveWorkbook;
objBook = Globals.ThisAddIn.Application.Workbooks.Open(IdsTemplatePath, 0, true, 5, "", "", true, XlPlatform.xlWindows, "\t", false, false, 0, true, false, false);                                
wkActive.Sheets.Add(objBook.Sheets[1], Type.Missing, Type.Missing, Type.Missing);
wkActive.Save();
wkActive.Close();

From an MVP:

I believe the Worksheet.Copy method is what you want. Assuming that you are using VSTO, the following code demonstrates one way to copy a worksheet from a non-VSTO workbook into the workbook in your VSTO customization. This particular example copies the first worksheet in a non-VSTO workbook named "MyWorkbook.xls" into a VSTO workbook, after "Sheet3".

Excel.Workbook workbook = Globals.ThisWorkbook.Application.Workbooks.Open(@"C:\MyWorkbook.xls", missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing);

Excel.Worksheet worksheet = workbook.Sheets[1] as Excel.Worksheet;

worksheet.Copy(missing, Globals.Sheet3.InnerObject);

The code first opens a non-VSTO workbook named "MyWorkbook.xls". The code then copies the first worksheet of this workbook into the VSTO workbook by calling the Copy method of the non-VSTO worksheet, and passing in the VSTO worksheet that you want to copy the non-VSTO worksheet after.

The only somewhat tricky VSTO-specific part of this code is the fact that it passes in the InnerObject property instead of Globals.Sheet3 into the Copy method. This is because Copy expects a Microsoft.Office.Interop.Excel.Worksheet, and the VSTO worksheet (that is, Globals.Sheet3) is a Microsoft.Office.Tools.Excel.Worksheet. The InnerObject property exposes the Microsoft.Office.Interop.Excel.Worksheet that underlies the Microsoft.Office.Tools.Excel.Worksheet.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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