表单控件是与Excel早期版本兼容的原始控件,通过表单控件,用户可以快速地将数据填写到模板文档中,如果你想在不使用VBA代码的情况下轻松引用单元格数据并与其进行交互,也可以使用表单控件。本文将介绍如何使用C#和​​Free Spire.XLS组件​​给Excel表格添加常见的表单控件例如文本框、单选按钮、复选框和组合框,以及如何删除现有的表单控件。


插入表单控件

//创建Workbook实例
Workbook workbook = new Workbook();
//添加工作表
Worksheet sheet = workbook.Worksheets[0];

//插入文本框
sheet.Range["A2"].Text = "姓名:";
ITextBoxShape textBox = sheet.TextBoxes.AddTextBox(2, 2, 18, 65);
textBox.Text = "肖恩";
textBox.Fill.ForeColor = Color.GreenYellow;
textBox.HAlignment = CommentHAlignType.Center;
textBox.VAlignment = CommentVAlignType.Center;

//插入单选按钮
sheet.Range["A4"].Text = "性别:";
IRadioButton radioButton = sheet.RadioButtons.Add(4, 2, 18, 65);
radioButton.CheckState = CheckState.Checked;
radioButton.Text = "男";

radioButton = sheet.RadioButtons.Add(4, 4, 18, 65);
radioButton.Text = "女";

//插入复选框
sheet.Range["A6"].Text = "爱好:";
ICheckBox checkBox = sheet.CheckBoxes.AddCheckBox(6, 2, 18, 65);
checkBox.CheckState = CheckState.Checked;
checkBox.Text = "摄影";

checkBox = sheet.CheckBoxes.AddCheckBox(6, 4, 18, 65);
checkBox.Text = "唱歌";


checkBox = sheet.CheckBoxes.AddCheckBox(6, 6, 18, 65);
checkBox.CheckState = CheckState.Checked;
checkBox.Text = "旅行";

//插入组合框
sheet["A8"].Text = "职业:";
sheet["A9"].Text = "学生";
sheet["A10"].Text = "教师";
sheet["A11"].Text = "医生";

IComboBoxShape comboBox = sheet.ComboBoxes.AddComboBox(8, 2, 18, 65);
comboBox.ListFillRange = sheet["A9:A11"];
comboBox.LinkedCell = sheet.Range["C8"];
comboBox.SelectedIndex = 2;

//保存文档
workbook.SaveToFile("AddFormControls.xlsx", ExcelVersion.Version2010);


C# Excel插入和删除表单控件_C#


删除表单控件


//创建Workbook实例
Workbook workbook = new Workbook();
//载入Excel文档
workbook.LoadFromFile("AddFormControls.xlsx");

//获取第一个工作表
Worksheet sheet = workbook.Worksheets[0];

//删除工作表中所有的复选框
for (int i = 0; i < sheet.CheckBoxes.Count; i++)
{
sheet.CheckBoxes[i].Remove();
}

//保存文档
workbook.SaveToFile("RemoveCheckBoxes.xlsx", ExcelVersion.Version2010);




C# Excel插入和删除表单控件_Excel_02