Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/303.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/excel/26.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
从Excel的下拉列表中检索所选值(在C#中创建)_C#_Excel_List_Validation - Fatal编程技术网

从Excel的下拉列表中检索所选值(在C#中创建)

从Excel的下拉列表中检索所选值(在C#中创建),c#,excel,list,validation,C#,Excel,List,Validation,我正在用C#创建一个包含下拉列表的Excel工作表。创建电子表格后,无法访问列表中的选定值(非编程方式)。当我使用数据验证在excel中创建列表时,效果很好。在C#中创建的列表似乎有所不同。在图中,您可以看到单元格AE中的值应为Z4的选定值,但它显示为0 我目前使用的代码是 public static void CreateList(Worksheet sheet, string[] items, int col, string row) { Range xls

我正在用C#创建一个包含下拉列表的Excel工作表。创建电子表格后,无法访问列表中的选定值(非编程方式)。当我使用数据验证在excel中创建列表时,效果很好。在C#中创建的列表似乎有所不同。在图中,您可以看到单元格AE中的值应为Z4的选定值,但它显示为0

我目前使用的代码是

    public static void CreateList(Worksheet sheet, string[] items, int col, string row)
    {
        Range xlsRange;
        DropDowns xlDropDowns;
        DropDown xlDropDown;

        xlsRange = sheet.get_Range(col + row, col + row);
        xlDropDowns = ((DropDowns)(sheet.DropDowns(Type.Missing)));

        xlDropDown = xlDropDowns.Add((double)xlsRange.Left, (double)xlsRange.Top, (double)xlsRange.Width, (double)xlsRange.Height, true);
        for (int i = 0; i < items.Length; i++)
            xlDropDown.AddItem(items[i], i + 1);
    }
我找到了为什么在使用下拉列表时出现“excel查找不可读内容”错误。其中一个下拉列表中逗号分隔的字符串太长。所以这两套代码都可以工作。第一种是组合框,您只能使用格式控制在每个组合框上检索选定值的索引。第二个是无法使用过长字符串创建的下拉列表(验证)

        public static void CreateList(Worksheet sheet, string[] items, int col, int row)
    {
        var flatList = string.Join(",", items);
        var cell = (Range)sheet.Cells[row, col];
        cell.Validation.Delete();
        cell.Validation.Add(XlDVType.xlValidateList, XlDVAlertStyle.xlValidAlertStop, XlFormatConditionOperator.xlBetween, flatList, Type.Missing);

        cell.Validation.IgnoreBlank = true;
        cell.Validation.InCellDropdown = true;
    }