Adding and deleting a label on Excel 2007 Worksheet
(Another snippet I originally posted to CodeKeep.)
Code:
// Required libs
using Microsoft.Office.Interop.Excel;
using Microsoft.Office.Tools.Excel.Extensions;
using Tools = Microsoft.Office.Tools;Range range = <get the target range to apply the label over>
string controlName = <unique name for the control to avoid collisions on other worksheets>// Add a control
Tools.Excel.Controls.Label lbl = worksheet.Controls.AddLabel(targetRange, controlName);// Add meaning to the label
lbl.Text = Title;
lbl.TextAlign = ContentAlignment.MiddleCenter;
lbl.BorderStyle = BorderStyle.FixedSingle;
lbl.ForeColor = Color.Black;
lbl.BackColor = Color.Green;// Delete a control
worksheet.Controls.Remove(controlName);
Usage:
//Add
lbl = worksheet.Controls.AddLabel(targetRange, controlName);// Delete
worksheet.Controls.Remove(controlName);
Notes:
If your range extends beyond a single cell, clear it before merging and applying the control. EG: range.Value2 = String.Empty; range.MergeCells = true; range.Value2 = Title;
Setting the cell background color and border, works around the label border artifacting. I was getting a strange green 1px line when I tried to define the borders in the label. I dropped the explicit settings and applied the border settings to the underlying cell and the green lines disappeared. It is probably something related to the Interop / Tool interaction.
If you are hitting a large number of cells, toggle Application.ScreenUpdating (false/true) to speed up the update and eliminate the screen flutter.
