从Excel

时间:2017-08-24 21:03:49

标签: c# .net excel visual-studio windows-applications

我有一张包含47列和大约100行的Excel工作表。我有一个带有文本字段,按钮和标签的Windows表单应用程序。

这就是我要做的事情:

当我在文本框中粘贴一个数字并单击该按钮时,它会搜索整个Excel工作表并获取该工作表(行,列)中特定字符串所在位置的行和列。这工作正常。我对表现很满意。这就是我真正想做的事情 -

在我到达搜索字符串的位置后,我想转到同一行的第45列并从该单元格中获取字符串,并将其显示在标签中。

这是我的代码(我没做的就是工作!)

string File_name = "C:\\Users\\v-nikken\\Documents\\My Received Files\\Case Wellness.xlsx";
Microsoft.Office.Interop.Excel.Application oXL = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook oWB;
Microsoft.Office.Interop.Excel.Worksheet oSheet;
try
{
    object missing = System.Reflection.Missing.Value;
    oWB = oXL.Workbooks.Open(File_name, missing, missing, missing, missing,
                    missing, missing, missing, missing, missing, missing,
                    missing, missing, missing, missing);
    oSheet = (Microsoft.Office.Interop.Excel.Worksheet)oWB.Worksheets[1];
    Microsoft.Office.Interop.Excel.Range oRng = GetSpecifiedRange(textBox_SRNumber.Text, oSheet);
    if (oRng != null)
    {

        //THIS IS THE LOGIC I HAVE TO TAKE VALUE FROM THE CELL TO THE LABEL
        //AND OBV IT ISN'T WORKING

        int IRPlace = Convert.ToInt32(oRng.Column) + 46; //This is obv wrong

        label_IRMet.Text = Convert.ToString(oSheet.Cells[Convert.ToInt32(oRng.Row), IRPlace]); //This also
        label_scope_sent.Text = IRPlace.ToString();

    }
    else
    {
        MessageBox.Show("Case number not found!", "Please try again");
    }
    oWB.Close(false, missing, missing);

    oSheet = null;
    oWB = null;
    oXL.Quit();
}
catch (Exception ex)
{
}

抱歉格式化。代码部分由于某种原因没有工作。

请帮助!!

Windows 10 - Excel 2016 - VS 2017 - .net 4.6.1

1 个答案:

答案 0 :(得分:1)

Microsoft.Office.Interop.Excel.Range valueForLabel=(Microsoft.Office.Interop.Excel.Range)yourSheet.Cells[oRng.Row,IRPlace]; string labelText=valueForLabel.Value.ToString();