每个新行的C#Excel下拉列表

时间:2013-10-14 11:22:25

标签: c# excel drop-down-menu office-interop

好的我正在创建一个需要执行的项目当您将任务导出到Excel并再次发布时,与TFS中的任务类似。 首先,我尝试使用必要的数据生成一个Excel文件,它应该填充一个带名称的下拉框,例如“Donald”,“Wilco”,“Jansen”等,使用以下代码我可以将它们添加到下拉列表并添加下拉到特定的单元格。但是我希望它可以让那个柱子有下拉列表 即 如果我去单元格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;

1 个答案:

答案 0 :(得分:1)

使用以下

解决了这个问题
        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;