How to get the value in an Excel dropdown using C#

前端 未结 1 1592
挽巷
挽巷 2021-01-19 20:09

I am looking for code to open and read an Excel file, any version of Excel, including 2010. One of my columns has a dropdown in it. I need to get the value of the selected

相关标签:
1条回答
  • 2021-01-19 20:54

    I know the VBA for both the ActiveX combo and the forms dropdown, and based on that, I can give you some very inexpert notes for c# for the forms dropdown, the combo eludes me as yet.

    Working with notes from: http://support.microsoft.com/kb/302084

    //Get a new workbook.
    oWB = (Excel._Workbook)(oXL.Workbooks.Open("C:\\Docs\\Book1.xls"));
    //3rd Sheet
    oSheet = (Excel._Worksheet)oWB.Sheets.get_Item(3);
    
    //This will return an index number
    var i = oSheet.Shapes.Item("Drop Down 1").ControlFormat.Value;
    //This will return the fill range
    var r = oSheet.Shapes.Item("Drop Down 1").ControlFormat.ListFillRange;
    oRng = oSheet.get_Range(r);
    //This will return the value of the dropdown, based on the index
    //and fillrange
    var a =oRng.get_Item(i).Value;
    
    //Just to check
    textBox1.Text = a; 
    

    This may help with an ActiveX combo, but I have only half got it to work:

    using MSForm = Microsoft.Vbe.Interop.Forms;
    
    <...>
    Excel.OLEObject cbOLEObj = (Excel.OLEObject)workSheet.OLEObjects("ComboBox1");
    MSForm.ComboBox ComboBox1 = (MsForm.ComboBox) cbOLEObj.Object; 
    Console.WriteLine(ComboBox1.Text);
    

    From: http://www.eggheadcafe.com/community/aspnet/66/10117559/excel-get-value-from-a-combobox.aspx

    0 讨论(0)
提交回复
热议问题