复制工作表 Excel VSTO C#
Copy Worksheet Excel VSTO C#
我正在尝试将现有 Excel 文件中的工作表复制到我当前的工作簿中。我有一个 Excel 加载项,代码如下:
string wsName = "template." + ((System.Windows.Forms.Button)sender).Tag + "." + ((System.Windows.Forms.Button)sender).Text;
Microsoft.Office.Interop.Excel.Application x = new Microsoft.Office.Interop.Excel.Application();
x.Visible = false; x.ScreenUpdating = false;
x.Workbooks.Open(Properties.Settings.Default.TemplatePath);
try
{
foreach (Worksheet w in x.Worksheets)
if (w.Name == wsName)
w.Copy(Type.Missing, Globals.ThisAddIn.Application.Workbooks[1].Worksheets[1]);
}
catch
{ }
finally
{
x.DisplayAlerts = false; x.Workbooks.Close(); x.DisplayAlerts = true; // close application with disabled alerts
x.Quit(); x.Visible = true; x.ScreenUpdating = true;
x = null;
}
我根据模板路径在后台打开了第二个excel实例。我找到工作表 w。这一切都很好,但是,我尝试将工作表复制到活动工作簿的内容无法正常工作。
当前的错误是找不到方法 Copy,但是当我删除参数时它执行正常。所以我假设我的问题出在 Globals.ThisAddIn.Appllication.Workbooks[1]。评估该参数会 return AddIn 中处于活动状态的当前工作簿。
事实是您正在尝试使用来自不同 processes/threads:
的对象
w.Copy(Type.Missing, Globals.ThisAddIn.Application.Workbooks[1].Worksheets[1]);
w
实例属于新创建的Excel实例,但参数来自插件实例。
如果您需要复制工作表,则需要在现有 Excel 实例中打开它。
我正在尝试将现有 Excel 文件中的工作表复制到我当前的工作簿中。我有一个 Excel 加载项,代码如下:
string wsName = "template." + ((System.Windows.Forms.Button)sender).Tag + "." + ((System.Windows.Forms.Button)sender).Text;
Microsoft.Office.Interop.Excel.Application x = new Microsoft.Office.Interop.Excel.Application();
x.Visible = false; x.ScreenUpdating = false;
x.Workbooks.Open(Properties.Settings.Default.TemplatePath);
try
{
foreach (Worksheet w in x.Worksheets)
if (w.Name == wsName)
w.Copy(Type.Missing, Globals.ThisAddIn.Application.Workbooks[1].Worksheets[1]);
}
catch
{ }
finally
{
x.DisplayAlerts = false; x.Workbooks.Close(); x.DisplayAlerts = true; // close application with disabled alerts
x.Quit(); x.Visible = true; x.ScreenUpdating = true;
x = null;
}
我根据模板路径在后台打开了第二个excel实例。我找到工作表 w。这一切都很好,但是,我尝试将工作表复制到活动工作簿的内容无法正常工作。 当前的错误是找不到方法 Copy,但是当我删除参数时它执行正常。所以我假设我的问题出在 Globals.ThisAddIn.Appllication.Workbooks[1]。评估该参数会 return AddIn 中处于活动状态的当前工作簿。
事实是您正在尝试使用来自不同 processes/threads:
的对象 w.Copy(Type.Missing, Globals.ThisAddIn.Application.Workbooks[1].Worksheets[1]);
w
实例属于新创建的Excel实例,但参数来自插件实例。
如果您需要复制工作表,则需要在现有 Excel 实例中打开它。