创建Office外接程序
通过工程创建一个外接程序
创建好后会有如下代码和引用
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using Excel = Microsoft.Office.Interop.Excel;
using Office = Microsoft.Office.Core;
using Microsoft.Office.Tools.Excel;
namespace MyfirstAddIn
{
public partial class ThisAddIn
{
private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
}
private void ThisAddIn_Shutdown(object sender, System.EventArgs e)
{
}
#region VSTO 生成的代码
/// <summary>
/// 设计器支持所需的方法 - 不要修改
/// 使用代码编辑器修改此方法的内容。
/// </summary>
private void InternalStartup()
{
this.Startup += new System.EventHandler(ThisAddIn_Startup);
this.Shutdown += new System.EventHandler(ThisAddIn_Shutdown);
}
#endregion
}
}
讲解一下作用
private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
//加载时会执行这里面的语句
}
private void ThisAddIn_Shutdown(object sender, System.EventArgs e)
{
//退出时会执行的应用
}
取得当前EXCEL控制权
public Excel.Application excelApp; //定义一个excell类型的变量
private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
excelApp = Globals.ThisAddIn.Application; //取得这个EXCEL控制权,赋值给变量
}
可以添加一个窗口
调用窗口
private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
excelApp = Globals.ThisAddIn.Application; //取得这个EXCEL控制权
Form1 frm = new Form1(); //创建一个窗口实例
frm.Show(); //显示窗口
}
启用的窗口与EXCEL交互
窗体中的代码
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;
using Office = Microsoft.Office.Core;
using Microsoft.Office.Tools.Excel;
namespace MyfirstAddIn
{
public partial class Form1 : Form
{
public Excel.Application ExcellApp; //创建ExellApp变量
public Form1()
{
InitializeComponent();
ExcelApp = Globals.ThisAddIn.Application; //获取当前Excel
}
private void button1_Click(object sender, EventArgs e)
{
ExcellApp.ActiveCell.Value = this.textBox1.Text;
}
}
}
d button1_Click(object sender, EventArgs e)
{
ExcellApp.ActiveCell.Value = this.textBox1.Text;
}
}
}
