Import Excel data to a Visual Studio Listbox

Asked

Viewed 1,317 times

1

I want a help on the title problem... I know I can make this import by VBA, but I want my program to detect the format . xls from a spreadsheet and extract your data to a Listbox within Visual Studio.

Has as?

  • You can use excel interoperability, so you read the file . xls and get the information you need.

  • Here’s an example in C# -> http://www.dontbreakthebuild.com/2011/01/30/excel-and-c-interop-with-net-4-how-to-read-data-from-excel/

  • This also works for Access?

  • If Access has Interop..

1 answer

2

If you are not afraid to work "in the dark", that is, without the help of Visual Studio error detection and Intellisense, you can refer to the Excel application as Object and use the same methods you would use in VBA. This is called Late Binding.

The Code below, for example, tries to appropriate an Excel instance that is already running (with Getobject()). If not, the error is dealt with by creating a new instance (with Createobject()).

From there, we’re on familiar ground. Open the workbook located in "C: Users Fulano Desktop Spreadsheet.xls" and scroll through the cells of the track "A1:A10" of the worksheet "Plan1". The values are copied to a List(Of String) where they will be available for you to use as you want:

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim Excel As Object
    Try
        Excel = GetObject(, "Excel.Application")
    Catch ex As Exception
        Excel = CreateObject("Excel.Application")
    End Try
    Excel.Visible = True
    Dim WorkBook As Object = Excel.Workbooks.Open("C:\Users\Fulano\Desktop\Planilha.xls")
    Dim WorkSheet As Object = WorkBook.Worksheets("Plan1")
    Dim MyList As New List(Of String)
    Dim Range = WorkSheet.Range("A1:A10")
    For Each Cell In Range.Cells
        MyList.Add(Cell.Value)
    Next
    WorkBook.Close
    Excel.Quit
    Excel = Nothing
    Stop
End Sub

I hope this helps.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.