Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding buttons to spreadsheets in .NET (VSTO)

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.

like image 791
mcoolbeth Avatar asked Jun 15 '10 14:06

mcoolbeth


People also ask

How do I add a sheet button in Excel?

On the Home tab, in the Cells group, click Insert, and then click Insert Sheet. Tip: You can also right-click the selected sheet tabs, and then click Insert. On the General tab, click Worksheet, and then click OK.

How do I create a VSTO add-in?

To create a new Excel VSTO Add-in project in Visual StudioUnder the expanded Office/SharePoint node, select the Office Add-ins node. In the list of project templates, select Excel 2010 Add-in or Excel 2013 Add-in. In the Name box, type FirstExcelAddIn. Click OK.


1 Answers

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.

like image 151
Mathias Avatar answered Sep 27 '22 19:09

Mathias