本文指导您如何使用 C# 在 Excel 中使用 ActiveX 控件。它详细介绍了如何设置 IDE 进行开发、定义流程的步骤列表以及使用 C# 添加 Excel Active X 控件 的示例代码。您将学习如何添加 ActiveX 控件,然后访问它来更新或读取控件值。
使用 C# 在 Excel 中添加 ActiveX 控件的步骤
- 将 IDE 设置为使用 Aspose.Cells for .NET 来处理 ActiveX 控件
- 使用 Workbook 类创建 Excel 文件以添加 ActiveX 控件
- 从工作表访问形状集合并调用 AddActiveXControl() 方法添加控件
- 访问 ActiveX 控件并发送其链接的单元格
- 要设置控件的特定属性,请对 ActiveX 控件进行类型转换并设置值
- 要更新或访问控件,请检查其控件类型并更新所需的值
这些步骤总结了如何使用 C# 在 Excel 中使用 ActiveX 控件。通过访问工作簿中的工作表的形状集合并调用 ShapeCollection 类中的 AddActiveXControl() 方法开始该过程。提供 ActiveX 控件的控件类型、目标单元格和大小,并将控件与单元格链接起来以操纵其值。
使用 C# 添加 ActiveX 命令按钮的代码
using Aspose.Cells; | |
using Aspose.Cells.Drawing; | |
using Aspose.Cells.Drawing.ActiveXControls; | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
new License().SetLicense("License.lic"); | |
// Create workbook object | |
Workbook wb = new Workbook(); | |
// Access first worksheet | |
Worksheet sheet = wb.Worksheets[0]; | |
// Add Command Button ActiveX Control inside the Shape Collection | |
Shape s = sheet.Shapes.AddActiveXControl(ControlType.CommandButton, 4, 0, 4, 0, 100, 30); | |
// Access the ActiveX control object and set its linked cell property | |
ActiveXControl c = s.ActiveXControl; | |
c.LinkedCell = "A1"; | |
// Add Toggle Button ActiveX Control inside the Shape Collection | |
Shape s1 = sheet.Shapes.AddActiveXControl(ControlType.ComboBox, 16, 0, 4, 0, 100, 30); | |
// Access the ActiveX control object and set its linked cell property | |
ActiveXControl c1 = s1.ActiveXControl; | |
c1.LinkedCell = "A4"; | |
ComboBoxActiveXControl comboControl = (ComboBoxActiveXControl)c1; | |
comboControl.Value = "A sample value for the ComboBox"; | |
// Save the workbook | |
wb.Save("Combo box with original value.xlsx"); | |
foreach (var shape in sheet.Shapes) | |
{ | |
// Access specific ActiveX Control and set its value | |
if (shape.ActiveXControl != null) | |
{ | |
// Access Shape ActiveX Control | |
ActiveXControl control = shape.ActiveXControl; | |
// Check for the target type | |
if (control.Type == ControlType.ComboBox) | |
{ | |
// Type cast ActiveXControl into ComboBoxActiveXControl and change its value | |
ComboBoxActiveXControl comboBoxActiveX = (ComboBoxActiveXControl)control; | |
comboBoxActiveX.Value = "A new value for the ComboBox"; | |
} | |
} | |
} | |
// Save the workbook in xlsx format | |
wb.Save("AddActiveXControls_out.xlsx", SaveFormat.Xlsx); | |
} | |
} |
此代码演示了如何使用 C# 在 Excel 工作表中添加 Combo Box ActiveX 控件。AddActiveXControl() 方法返回对新添加的形状的引用,您可以使用该引用来设置链接的单元格和其他属性,例如字体、颜色、阴影和文本对齐等。同样,如果您将形状强制转换为特定控件,您将获得大量用于自定义控件的属性。
本文教我们如何在 Excel 文件中添加和访问 ActiveX 控件。有关在 Excel 文件中添加图像,请参阅 如何使用 C# 在 Excel 单元格中添加图像 上的文章。