获取excel activeworkbook activesheet activecell的值并放入到ac#winform文本框中

我试图得到一个string值,可能是在activecell中的任何Excel 2010工作簿,并在ac#应用程序winform文本框中使用该值。 我正在使用vs2015和excel 2010。

这是我试过的没有成功的。

//Get active excel instance Excel.Application xlApp = (Excel.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application"); //Get active excel workbook Excel.Workbook xlWorkBook = (Excel.Workbook)xlApp.ActiveWorkbook; //Get active excel worksheet Excel.Worksheet xlWorkSheet = (Excel.Worksheet)xlWorkBook.ActiveSheet; //Get value for excel string AValue = xlWorkSheet.Cells[2, 2].ToString(); //Put value in c# winform textbox txtSearchPattern.Text = AValue; 

使用Microsoft.Office.Interop.Excel

Range.Cells集合的成员是Range对象,而不是string。 尝试Cells[x,y].Value2来检索单元格的值。

此外,当前select的Range对象是一个应用程序范围的variablesApplication.Selection ,因此您应该可以使用Application.Selection.Cells[1,1].Value2检索活动select区域中最左上angular的单元格的值引用任何工作簿/工作表。

编辑:在这种情况下,你可能最好使用Application.Activecell因为select可以返回非范围对象(图片等)。

我不知道这是否是最好的方法,但它似乎允许程序运行并捕获nullexception错误。

  try { //Get active excel instance Excel.Application xlApp = (Excel.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application"); //Get active excel workbook Excel.Workbook xlWorkBook = (Excel.Workbook)xlApp.ActiveWorkbook; //Get active excel worksheet Excel.Worksheet xlWorkSheet = (Excel.Worksheet)xlWorkBook.ActiveSheet; //Get value for excel string AValue = xlApp.ActiveCell.Value2.ToString(); //Return value to winform textbox txtSearchPattern.Text = AValue; } catch(NullReferenceException) { MessageBox.Show("ActiveCell was null"); } 

使用单击事件处理程序( button1_Click )将下面的代码分配给具有button( button1 )的WinForm,如下所示:

 using Microsoft.Office.Excel.Interop; namespace XYZ { public partial class ABC : Form { Excel.Range activecell = null; Excel.Application xlApp = (Excel.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application"); public ABC() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { if (xlApp.Selection is Excel.Range) { activecell = xlApp.Selection as Excel.Range; //Return value to winform textbox txtSearchPattern.Text = activecell.Value2.ToString(); } } } } 

当您单击包含值的Excel工作表中的单元格,然后单击button1时 ,文本框( txtSearchPattern )的值已相应更新。