如何使用C#从Excel中读取Comboboxes值

时间:2017-10-15 07:51:58

标签: c# excel combobox

在我的应用程序中,我需要创建一个包含几个组合的excel文件。我已经创建了它。 enter image description here

现在我必须从excel中读取这些组合的值。 我找到了一个从excel Read From Excel

中读取的链接

但在我的代码中我找到了这个..

enter image description here

enter image description here

这是我的代码

Microsoft.Office.Interop.Excel.Application oXL = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel._Workbook oWB;
Microsoft.Office.Interop.Excel._Worksheet oSheet;
Microsoft.Office.Interop.Excel.Range oRng;

//Get a new workbook.
oWB = (Microsoft.Office.Interop.Excel._Workbook)(oXL.Workbooks.Open("C:\\TopicUpload_2017October14.xls"));
//3rd Sheet
oSheet = (Microsoft.Office.Interop.Excel._Worksheet) oWB.Sheets.get_Item(1);

 Microsoft.Office.Interop.Excel.DropDowns allDropDowns = oSheet.DropDowns(Type.Missing);
 Microsoft.Office.Interop.Excel.DropDown oneDropdown = allDropDowns.Item("2");

现在我怎么能得到这个下拉列表的选定文本..当我检查时我得到了

oneDropdown.ListCount = 5.0; // items count of second drop down, which is true

但无法获得选定的文字。

oneDropdown.Text

1 个答案:

答案 0 :(得分:0)

搜索后,我能够得到它。

#region Read value from excel combobox
                    Microsoft.Office.Interop.Excel.Application oXL = new Microsoft.Office.Interop.Excel.Application();
                    Microsoft.Office.Interop.Excel._Workbook oWB;
                    Microsoft.Office.Interop.Excel._Worksheet oSheet;
                    Microsoft.Office.Interop.Excel.Range oRng;

                    //Get a new workbook.
                    oWB = (Microsoft.Office.Interop.Excel._Workbook)(oXL.Workbooks.Open("C:\\TopicUpload_2017October14.xls"));
                    //3rd Sheet
                    oSheet = (Microsoft.Office.Interop.Excel._Worksheet)oWB.Sheets.get_Item(1);

                    Microsoft.Office.Interop.Excel.DropDowns allDropDowns = oSheet.DropDowns(Type.Missing);
                    Microsoft.Office.Interop.Excel.DropDown oneDropdown = allDropDowns.Item("1"); // first combo
                    string selectedText = oneDropdown.get_List(oneDropdown.ListIndex); 
    #endregion