获取excel activeworkbook activesheet activecell值并放入c#winform文本框

时间:2016-04-29 17:49:17

标签: c# .net excel

我正在尝试获取可能位于activecell中的任何excel 2010工作簿中的字符串值,并在c#applications 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;

3 个答案:

答案 0 :(得分:0)

使用Microsoft.Office.Interop.Excel

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

此外,当前选定的Range对象是应用程序范围的变量Application.Selection,因此您应该能够使用Application.Selection.Cells[1,1].Value2检索活动选择中最左上角的单元格的值,而不引用任何变量Application.Activecell工作簿/工作表。

编辑:在这个例子中,您可能最好使用int main() { int arr[4][5]; int i,j; FILE *inp; inp = fopen("votes.txt", "r"); for (i = 0; i < 5; i++) { for (j = 0; j < 4; j++) fscanf(inp, "%d", &arr[i][j]); fclose (inp); } for (i = 0; i < 5; i++) { for (j = 0; j < 4; j++) printf("%d",arr[i][j]); printf("\n"); } } ,因为选择可以返回非范围对象(图片等)。

答案 1 :(得分:0)

我不确定这是否是最佳方式,但它似乎允许程序运行并捕获空异常错误。

            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");
            }

答案 2 :(得分:0)

将以下代码分配给具有按钮( button1 )的WinForm,其中包含单击事件处理程序( button1_Click ),如下所示:

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 )的值会相应更新。