更改Excel C#下拉列表中的值

本文关键字:下拉列表 Excel 更改 | 更新日期: 2023-09-27 18:08:53

所以我问过如何使用c#更改excel中单元格的值,但如果我想更改下拉列表的值,该怎么办。我用于修改图纸的代码如下。感谢您的帮助。

 public virtual Object ActiveSheet { get; set; }
 private void button3_Click(object sender, EventArgs e)
 {
 var sheet = (Excel._Worksheet)this.ActiveSheet; 
 sheet.Cells[6, 6] = "6";
 }

我打开了工作表,但当它进入列表时,它会给我NullReferenceException。

更改Excel C#下拉列表中的值

我花了很长时间才发现,请使用它!!

  using Excel = Microsoft.Office.Interop.Excel;
  public virtual Object ActiveSheet { get; set; }
  private void button15_Click(object sender, EventArgs e)
    {
        //Gets ActiveSheet to Modify
        Excel.Application oXL;
        Excel.Workbook oWB;
        Excel.Worksheet oSheet;
        //Start Excel and get Application object.
        oXL = (Excel.Application)Marshal.GetActiveObject("Excel.Application"); 
        oXL.Visible = true;
        oWB = (Excel.Workbook)oXL.ActiveWorkbook; 
        oSheet = (Excel.Worksheet)oWB.ActiveSheet;
        //Generate Linear Guide Supports using Design Table in Solidworks
        if (comboBox1.Text == "0")//no external rails
        {
            oSheet.Cells[6, 4] = "0"; //Change Value in Cell in Excel Cell Location [y-axis, x-axis]
        }
        //Quit Excel
        oXL.Quit();
    }

使用此选项浏览下拉列表。如果您正在使用下拉对象。我们正在使用shapes.item

您需要从excel中识别形状对象的名称。

var control = xlWorksheet.Shapes.Item("Drop Down 22").ControlFormat;
control.ListIndex = 5; ''This allows you to change the drop down to 5th element

如果您试图更改基于excel表格单元格的组合框,您可以直接更改单元格值

 Excel.Range xlRangeloc= xlWorksheetH.get_Range("D5");
                            xlRangeloc.Value = "OptionOne";
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;
//create exel
oWB = oXL.Workbooks.Open(@"C:'Users''Desktop'Test.xlsx");
oXL.Visible = true;//Can make it false when don't want to see the excel file
//give u name of workbook
 string ExcelWorkbookname = oWB.Name;
// statement get the worksheet count  
 int worksheetcount = oWB.Worksheets.Count;
string path = oWB.Path;
oSheet = (_Worksheet)oWB.Sheets.get_Item(1);
string str = oSheet.Name;
//IMP: on Excel right click on drop down u can see the drop down name on left top most corner which u r providing below.
// It can be anything like Drop Down 5,Drop Down 6,Drop Down 7 etc
  var dropdownValue= oSheet.Shapes.Item("Drop Down 5").ControlFormat; 
dropdownValue.ListIndex = 2; //This allows you to change the drop down to 2nd element

//这段代码可以工作,但Interop非常非常慢。而是使用Oledb