Inserting Sheet from another Workbook in Excel Add-in

时间:2018-04-18 18:11:33

标签: c# excel vsto

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);
}

2 个答案:

答案 0 :(得分:3)

这是一个奇怪的Excel问题。我们已通过HKEY_CURRENT_USER \ Software \ Microsoft \ Office \ 16.0 \ Common \ General \ DisableBootToOfficeStart中的注册表项禁用了Excel欢迎页面。由于一些奇怪的原因,这使得此代码无法按预期工作。

答案 1 :(得分:1)

试试这个

            // 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);