Adding buttons to spreadsheets in .NET (VSTO)

2019-03-25 21:52发布

问题:

Using VSTO or some related technology, is it possible to programmatically embed a button in a cell of an Excel worksheet, and configure it to call a C# function when it is clicked?

How?

Thanks.

回答1:

With a VSTO document customization (i.e., a Workbook with .Net code attached), you can add and remove controls at runtime to the Worksheets of the project. The following code illustrates the idea:

 public partial class Sheet1
 {
     private void Sheet1_Startup(object sender, System.EventArgs e)
     {
        var button = this.Controls.AddButton(10, 10, 50, 50, "My Button");
        button.Text = "My Button";
        button.Click += new EventHandler(button_Click);
     }

     void button_Click(object sender, EventArgs e)
     {
        MessageBox.Show("I was clicked!");
     }

You could also add controls dynamically to documents via a VSTO add-in, using code along these lines (thanks to people on the VSTO forum for that one):

var workSheet = (Excel.Worksheet) sheet;
var vstoSheet = workSheet.GetVstoObject();
var button = vstoSheet.Controls.AddButton(50, 50, 100, 50, "Test");
button.Text = "Dynamic Button!";

Check this post by Eric Carter for more info.



回答2:

Here is the code which works for me in VSTO Add-in (modified version of Mathias's answer):

using Excel = Microsoft.Office.Interop.Excel;
using ExcelTools = Microsoft.Office.Tools.Excel;

public void AddButtonToWorksheet()
{
  Excel.Worksheet worksheet = (Excel.Worksheet)Globals.ThisAddIn.Application.ActiveWorkbook.ActiveSheet;
  ExcelTools.Worksheet vstoSheet = Globals.Factory.GetVstoObject(worksheet);

  Button button = new Button();
  button.Text = "Dynamic Button!";
  vstoSheet.Controls.AddControl(
    button, 50, 50, 100, 50, "TestButton");
}