C# 在Excel中插入表单控件
1、下载安装该组件后,注意在项目程序中添加引用Spire.Xls.dll(dll文件可在安装路径下的Bin文件夹中获取),如下图所示

1、using Spire.Xls;
using Spire.Xls.Core;
using System.Drawing;
namespace FormControls_XLS
{
class Program
{
static void Main(string[] args)
{
//实例化一个Workbook类实例,并获取第1个工作表
Workbook workbook = new Workbook();
Worksheet sheet = workbook.Worksheets[0];
//设置表格行高、列宽
sheet.Range["A1:F1"].ColumnWidth = 15F;
sheet.Range["A1:B12"].RowHeight = 20F;
//插入文本框控件,指定文本框位置、大小以及文本对齐方式
sheet.Range["A1"].Text = "姓名:";
ITextBoxShape textBox = sheet.TextBoxes.AddTextBox(1, 2, 25, 110);
textBox.Text = "John";
textBox.HAlignment = CommentHAlignType.Center;
textBox.VAlignment = CommentVAlignType.Center;
//插入单选按钮,指定单元格位置
sheet.Range["A3"].Text = "性别:";
IRadioButton radioButton = sheet.RadioButtons.Add(3, 2, 20, 80);
radioButton.CheckState = CheckState.Checked;
radioButton.Text = "女";
radioButton = sheet.RadioButtons.Add(3, 3, 20, 80);
radioButton.Text = "男";
//插入复选框并指定单元格位置
sheet.Range["A5"].Text = "所在行业:";
ICheckBox checkBox = sheet.CheckBoxes.AddCheckBox(5, 2, 18, 65);
checkBox.CheckState = CheckState.Checked;
checkBox.Text = "教育";
checkBox = sheet.CheckBoxes.AddCheckBox(5, 3, 18, 65);
checkBox.Text = "医疗";
checkBox = sheet.CheckBoxes.AddCheckBox(5, 4, 18, 65);
checkBox.Text = "IT";
checkBox = sheet.CheckBoxes.AddCheckBox(5, 5, 18, 65);
checkBox.Text = "零售";
checkBox = sheet.CheckBoxes.AddCheckBox(5, 6, 18, 65);
checkBox.Text = "其他";
//插入组合框,并指定单元格位置、大小
sheet["A7"].Text = "年龄(段):";
sheet["A8"].Text = "<18";
sheet["A9"].Text = "18<Y<30";
sheet["A10"].Text = "30<Y<50";
IComboBoxShape comboBox = sheet.ComboBoxes.AddComboBox(7, 2, 23, 100);
comboBox.ListFillRange = sheet["A8:A10"];
//指定组合框的关联单元格
sheet["A12"].Text = "代表人群类别:";
comboBox.LinkedCell = sheet.Range["B12"];
comboBox.SelectedIndex = 1;
//保存文档
workbook.SaveToFile("AddFormControls.xlsx", ExcelVersion.Version2010);
System.Diagnostics.Process.Start("AddFormControls.xlsx");
}
}
}
2、运行程序后,生成文档:
