如何从c#或vb.net读取Excel下拉列表或checkbox的值?

我正在使用Microsoft.Office.Interop.Excel来读取工作表单元格的值,但我找不到显示如何读取下拉列表,checkbox和选项button的信息。

谢谢!

显然,直接访问DropDowns集合是一个烦恼 。 解决方法是访问包含下拉列表的单元格的Validation属性,获取它的公式,然后parsing列表的位置。

Excel.Range dropDownCell = (Excel.Range)ws.get_Range("A1", "A1"); //cell containing dropdown string formulaRange = dropDownCell.Validation.Formula1; string[] splitFormulaRange = formulaRange.Substring(1,formulaRange.Length-1).Split(':'); Excel.Range valRange = (Excel.Range)ws.get_Range(splitFormulaRange[0], splitFormulaRange[1]); for (int nRows = 1; nRows <= valRange.Rows.Count; nRows++) { for (int nCols = 1; nCols <= valRange.Columns.Count; nCols++) { Excel.Range aCell = (Excel.Range)valRange.Cells[nRows, nCols]; System.Console.WriteLine(aCell.Value2); } } 

经过大量的头部搔抓,我得到以下工作只有下拉菜单 。 我也有一个类似,但不完全相同的RadioButtons解决scheme,但没有尝试checkbox。

在Interop返回一个System.Object的时候,这样做并没有那么简单,在这个System.Object中我们可以期待一个数组(VSdebugging器告诉我它在技术上是一个System.Object[*] ,但无论如何,我都不能像数组那样parsing它) ,或者是1索引的ControlFormat.List[]数组。 万岁!

下面的代码假定打开的工作簿和目标dropDown的名称

 Worksheet worksheet = (Worksheet)workbook.Worksheets[worksheetName]; var control = worksheet.Shapes.Item(dropdownName).ControlFormat; var vl = GetDropdownList(control); var targetIndex = IndexOfMatch(targetValue, vl); control.Value = targetIndex; // control.List returns a System.Object that may indeed be an array, but it's hard to parse in that format // let's loop through it, explicitly casting as we go private List<string> GetDropdownList(ControlFormat control) { var newList = new List<string>(); // haw! the Excel control-list is one-indexed! And the last item is equal to the count-index. for (int i = 1; i <= control.ListCount; i++) { newList.Add((string)control.List[i]); } return newList; } private int IndexOfMatch(string targetValue, List<string> vals) { int indexMatch = vals.IndexOf(targetValue); // the Excel target is 1-indexed, so increase by one return ++indexMatch; } 

我宁愿在OpenXmlSDK中这样做 – 但是如果我能弄明白怎么做的话。 我可以find附加到单元格的DataValidation,parsing它指向的工作表和单元格,从SharedStringTable中获取它们的SharedString值 – 但不pipe我做什么,我都不能写回任何数据。 FEH。

Exel我从地狱的心里刺伤了你。

 string selectedText = myDropDown.get_List(myDropDown.ListIndex);