How to import data from excel to textbox in WPF?

0

I am working on a project , and i basically have to display data ( cell wise) from an excel file to a textbox. I used the following code

Option Explicit On
Imports System.IO
Imports Microsoft.VisualBasic.FileIO

Partial Public Class Window2
    Dim objexcel As New Excel._ExcelApplication
    Dim objwork As Excel._ExcelSheet
    Dim objworksheet As Excel.Worksheet

    Private Sub Window1_Loaded(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles Window1.Loaded
        objwork = objexcel.Workbooks.open("D:\jkj.xlsx")
        objworksheet = CType(objwork.Worksheets.Item("Sheet1"), Excel.Worksheet)
        TextBox1.Text = objwork.cells(1, 1).text
        Textbox2.Text = objwork.cells(2, 1).text
        objexcel.Workbooks.close()
        objexcel.Workbooks.Quit()
    End Sub
End Class

But it is showing the following error

Member not found. (Exception from HRESULT: 0x80020003 (DISP_E_MEMBERNOTFOUND))

Can someone suggest whats wrong with the code? I have searched and read high and low over the net.

Thank you!

wpf
excel
asked on Stack Overflow Oct 17, 2013 by stellaluna • edited Oct 17, 2013 by Sheridan

1 Answer

0

You made a few mistakes:

  1. objwork.cells(1, 1) -> Should be objworksheet.cells(1, 1)
  2. objexcel.Workbooks.Quit() -> Should be objexcel.Quit()
  3. objworksheet.cells(1, 1).text -> You should split getting the Range object and getting it's text property. It's a general rule of thumb: "Never use 2 dots with COM objects." Not obeying it leads to leaving Excel's thread running even after user closes client app.

You should also consider securing your code with the try-catch block - from my experience there are many unexpected possibilities of getting an exception while working with Office via COM.

answered on Stack Overflow Oct 17, 2013 by Rav

User contributions licensed under CC BY-SA 3.0