每个新行上的 C# Excel 下拉列表
本文关键字:Excel 下拉列表 新行 | 更新日期: 2023-09-27 18:35:27
好的,我正在创建一个项目,当您将任务导出到 Excel 并再次发布时,该项目需要与 TFS 中的任务类似。首先,我尝试使用必要的数据生成一个Excel文件,它应该用名称填充一个下拉框,例如"唐纳德","威尔科","詹森"等,使用以下代码我可以将它们添加到下拉列表中并将下拉列表添加到特定的单元格。但我希望它使该列具有下拉列表即如果我转到单元格 A1,它应该有一个下拉列表,如果我转到单元格 A2,它应该有一个下拉列表A(x) 应该始终有一个 drowpdown,所以如果我添加信息并转到新行,它应该有下拉菜单。
目前我有以下代码要开始,但不知道从这里开始
var oMissing = Type.Missing;
var excel = new Application();
var wb = excel.Workbooks.Add(1);
var sh = wb.Sheets.Add();
sh.Name = "TestSheet";
sh.Cells[1, "A"].Value2 = "SNO";
sh.Cells[2, "B"].Value2 = "A";
sh.Cells[2, "C"].Value2 = "1122";
var range = sh.Range["A1","A1"];
var xlDropDowns = ((DropDowns)(sh.DropDowns(oMissing)));
var xlDropDown = xlDropDowns.Add((double)range.Left, (double)range.Top, (double)range.Width, (double)range.Height, false);
var items = new[] { "Name1", "Name2", "Name3" };
//Add items into drop down list
for (int i = 0; i < items.Length; i++)
{
xlDropDown.AddItem(items[i], i + 1);
}
//wb.Close(true);
//excel.Quit();
excel.Visible = true;
用以下内容解决了它
var oMissing = Type.Missing;
var excel = new Application();
var wb = excel.Workbooks.Add(1);
var sheet = wb.Sheets.Add();
sheet.Name = "ClientEditSheet";
sheet.Visible = false;
sheet.Range["A1"].Value = "Name1";
sheet.Range["A2"].Value = "Name2";
sheet.Range["A3"].Value = "Name3";
sheet.Range["A4"].Value = "Name4";
var sheet2 = wb.Sheets["Sheet1"];
Range validatingCellsRange = sheet2.Range["B1"].EntireColumn;
var lookupValues = "=ClientEditSheet!$" + "A" + "$1:$" + "A" + "$14";
validatingCellsRange.Validation.Delete();
validatingCellsRange.Validation.Add(XlDVType.xlValidateList,
XlDVAlertStyle.xlValidAlertInformation,
XlFormatConditionOperator.xlBetween, lookupValues, Type.Missing);
validatingCellsRange.Validation.IgnoreBlank = true;
validatingCellsRange.Validation.InCellDropdown = true;
//wb.Close(true);
//excel.Quit();
excel.Visible = true;