使用C#获取Excel选项框的值

我想用c#打开一个现有的Excel文件,读取现有的选项button(真/假)的值,并将值写入另一个单元格。

我可以打开文件,但我坚持如何获得选项button的值。 选项框是一个表单控件而不是一个activeX控件。

下面的代码工作,直到最后一行,然后它生成一个COMexception。

Excel.Application xlApp = new Excel.Application(); //creates the application xlApp.Visible = true; string wbPath = @"C:\path.xlsx"; Excel.Workbook xlWb = xlApp.Workbooks.Open(wbPath, 0, false, 5, "", "", false, Excel.XlPlatform.xlWindows, "", true, false, 0, true, false, false); //opens the specific file Excel.Sheets xlS = xlWb.Worksheets; string currentSheet = "1"; Excel.Worksheet xlWS = (Excel.Worksheet)xlS.get_Item(currentSheet); Excel.OptionButton opt1 = (Excel.OptionButton)xlWS.OptionButtons(1); 

我很新的编程。 任何帮助或资源将不胜感激。

Office程序互操作编程的秘密之一是创build所需操作的macros。 一旦保存,请查看调用不同的互操作方法的VB代码。 这些方法与您在C#程序中必须处理的方法是一样的。

如果没有别的,它可以帮助您研究可能导致其他编程方式所需的操作。

在Excel中,开发者选项卡默认不显示,您需要打开它来执行macros并运行VB编辑器。

我想到了。 感谢OmegaMan推动正确的方向。 我会在这里发布代码,以防有类似问题的人需要帮助。

  Excel.Application xlApp = new Excel.Application(); //creates the application xlApp.Visible = true; //change to false for final version string wbPath = @"C:\path.xlsx"; //sets the path Excel.Workbook xlWb = xlApp.Workbooks.Open(wbPath, 0, false, 5, "", "", false, Excel.XlPlatform.xlWindows, "", true, false, 0, true, false, false); //creates the workbook and opens the specific file Excel.Worksheet xlWS = (Excel.Worksheet)xlWb.ActiveSheet; //sets the active sheet Excel.Range gr1Text = xlWS.get_Range("e20"); Excel.Range xlRngP19 = xlWS.get_Range("p19"); Excel.Range xlRngQ19 = xlWS.get_Range("q19"); xlRngP19.Value = gr1Text; string[] rating = { "Exceptional", "Demonstrates skill level necessary for position", "Needs Improvement", "N/A" }; bool opt1; opt1 = xlApp.ActiveSheet.OptionButton2.Value; bool opt2; opt2 = xlApp.ActiveSheet.OptionButton1.Value; bool opt3; opt3 = xlApp.ActiveSheet.OptionButton3.Value; bool opt4; opt4 = xlApp.ActiveSheet.OptionButton4.Value; bool chBox1; chBox1 = xlApp.ActiveSheet.CheckBox1.Value; Excel.Range xlRngP20 = xlWS.get_Range("p20"); if (opt1 == true) { xlRngP20.Value = rating[0]; } else if (opt2 == true) { xlRngP20.Value = rating[1]; } else if (opt3 == true) { xlRngP20.Value = rating[2]; } else if (opt4 == true) { xlRngP20.Value = rating[3]; } else { xlRngP20.Value = "**NOT RECORDED**"; } if (chBox1 == true) { xlRngQ19.Value = "Growth Opportunity"; } xlWb.Close(true); xlApp.Quit(); //closes the file 

感谢分享Akb。 这里是如何设置值:

 if (job == "Y") { ((Excel.OptionButton)gma.OptionButtons("jobYes")).Value = true; } else { ((Excel.OptionButton)gma.OptionButtons("jobNo")).Value = true; }