I am trying to copy a sheet from an existing Excel Workbook and paste it into the current workbook using an Excel Add-in. I am using the following code but it is throwing an exception:
private void insertSamplingWksht_Click(object sender, RibbonControlEventArgs e)
{
Microsoft.Office.Interop.Excel.Application xlApp = new
Microsoft.Office.Interop.Excel.Application();
Workbook templateWorkbook = xlApp.Workbooks.Open(templatePath);
Worksheet from = (templateWorkbook.Sheets[1] as Worksheet); // Get first sheet
Worksheet to = (Globals.ThisAddIn.Application.ActiveWorkbook.ActiveSheet as Worksheet);
from.Copy(to, Type.Missing); // Throws System.Runtime.InteropServices.COMException: 'No such interface supported'
}
I also tried the following which did not work either.
private void insertSamplingWksht_Click(object sender, RibbonControlEventArgs e)
{
string templatePath = @"path to file";
Microsoft.Office.Interop.Excel.Application xlApp = Globals.ThisAddIn.Application;
var activeWkbName = xlApp.ActiveWorkbook.Name;
int beforeCount = xlApp.Workbooks.Count; // 1
var templateWorkbook = xlApp.Workbooks.Open(templatePath);
var from = (templateWorkbook.Sheets[1] as Microsoft.Office.Interop.Excel.Worksheet);
int afterCount = xlApp.Workbooks.Count; // also 1
xlApp.Workbooks[activeWkbName].Activate(); // COMException: 'Invalid index.
from.Copy(xlApp.ActiveWorkbook.ActiveSheet, Type.Missing);
}
It was a strange Excel issue. We had disabled the Excel welcome page via a registry key at HKEY_CURRENT_USER\\Software\\Microsoft\\Office\\16.0\\Common\\General\\DisableBootToOfficeStart. For some strange reason this stopped this code from working as expected.
Try this
// no need to open another Excel instance
Microsoft.Office.Interop.Excel.Application xlApp = Globals.ThisAddIn.Application;
// get the name of the active workbook to be able to return back
var activeWkbName = xlApp.ActiveWorkbook.Name;
// open the template workbook - which will become active then
var templateWorkbook = xlApp.Workbooks.Open(templatePath);
var from = (templateWorkbook.Sheets[1] as Microsoft.Office.Interop.Excel.Worksheet);
// active the original one
xlApp.Workbooks[activeWkbName].Activate();
from.Copy(xlApp.ActiveWorkbook.ActiveSheet, Type.Missing);
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.