Adding buttons to spreadsheets in .NET (VSTO)

前端 未结 2 566
故里飘歌
故里飘歌 2021-02-15 08:01

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 click

2条回答
  •  情深已故
    2021-02-15 08:54

    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.

提交回复
热议问题