0

So after some changes, I have used this code:

Dim XlApp = New Microsoft.Office.Interop.Excel.Application
Dim oBook As Object = XlApp.Workbooks.Open("C:\file.xlsx")
Dim oSheet As Object = oBook.Worksheets(1)

Private Sub form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Dim StartedRow As Integer
    Dim TotalRows As Integer

    TotalRows = XlApp.ActiveWorkbook.Sheets(1).Range("a1").CurrentRegion.Rows.Count

    For StartedRow = 1 To TotalRows
        Me.ListBox1.Items.Add(oSheet.Cells(StartedRow, 1).text)
        Me.ListBox1.Items.Add(oSheet.Cells(StartedRow, 2).text)
    Next

    MessageBox.Show("Succesful")

This one works but only shows two rows which is not in proper order, I need to show the whole file. Sorry, since I'm new to Stack Overflow I find it kinda confusing for now :)

  • 1
    It is really hard to help you without the code that is causing the exception. Please edit your question to include the code and format it as code. – Mary Aug 22 '20 at 16:31
  • You can display it very well. Hmm or maybe..Seems you haven’t used the right solution from the web or maybe is all bad solutions :) . However take care about Mary’s advice ;) – G3nt_M3caj Aug 22 '20 at 16:42
  • I have not really used a code. Just trying codes from the Internet. I'm just asking for an example of what code I can use please. Some codes I'm getting only display a specific column etc, but I need to display the whole table in the excel sheet. @Mary – Wakashio1234 Aug 22 '20 at 17:11
  • @G3nt_M3caj ... – Wakashio1234 Aug 22 '20 at 17:11
  • I never put a negative score, never (to be honest two by mistake using SO, is part of my being, I'm only for positive things) but, I bet your question is closed by tonight how is writed/asked – G3nt_M3caj Aug 22 '20 at 17:31
  • @Aish22222 It will take some work on your part, but [How to read file using NPOI](https://stackoverflow.com/questions/5855813/how-to-read-file-using-npoi/30918598) includes an answer which opens an Excel file and converts it into a DataTable. You can then use the DataTable as the DataSource for the ListBox, remembering to set the DataMember property to the name of the column you want to use. – Andrew Morton Aug 22 '20 at 17:50
  • Debug your code. You're a developer, not a user, so don't act like a user. Run your project in the debugger, set a breakpoint and then step through the code line by line, examining the state at each step. You can then see exactly when and where the behaviour deviates from your expectations. If you still can't solve it, at least you can provide us with all the relevant information. – jmcilhinney Aug 23 '20 at 05:07
  • You are getting only 2 rows because you are not looping through all columns... you have hard coded 1 and 2 in your for loop listbox add item lines... – Bharath Aug 23 '20 at 08:47
  • @jimcilhinney I'm not a professional developer I'm just a student and I'm still learning, I don't really know what you're talking about. – Wakashio1234 Aug 23 '20 at 18:46
  • @Bharath thanks for the info, but can you give a help how to loop it? – Wakashio1234 Aug 23 '20 at 18:47

3 Answers3

0

You need to declare your variables as specific types so you can use the properties and methods of that type. In general, don't let variables flap about as Object unless absolutely necessary.

I used .UsedRange to get row count. It seemed a bit simpler.

I used an interpolated string, indicated by the $, to get the range. In versions of Visual Studio prior to 2015 you will have to use

String.Format("A{0}", RowNum)

Excel is hard to get rid of. Therefore, put the Excel stuff in a separate method and add the two GC calls when the method returns.

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    DoExcelThing()
    GC.Collect()
    GC.WaitForPendingFinalizers()
    'Even doing this will still leave a Zoombie Excel in Task Manager when debugging. (Hopefully not release)
    MessageBox.Show("Succesful")
End Sub

Private Sub DoExcelThing()
    Dim XlApp As New Microsoft.Office.Interop.Excel.Application
    Dim oBook As Workbook = XlApp.Workbooks.Open("C:\file.xlsx")
    Dim oSheet As Worksheet = CType(oBook.Worksheets(1), Worksheet)
    Dim TotalRows = oSheet.UsedRange.Rows.Count
    For RowNum = 1 To TotalRows
        ListBox1.Items.Add(oSheet.Range($"A{RowNum}").Value)
        ListBox1.Items.Add(oSheet.Range($"B{RowNum}").Value)
    Next
End Sub
Mary
  • 14,926
  • 3
  • 18
  • 27
0

@Wakashio1234 This Will loop through all the cells..

TotalRows = XlApp.ActiveWorkbook.Sheets(1).Range("a1").CurrentRegion.Rows.Count
Totalcolumns = XlApp.ActiveWorkbook.Sheets(1).Range("a1").CurrentRegion.columns.Count
For StartedRow = 1 To TotalRows
   For Startedcolumn = 1 To Totalcolumns
       Me.ListBox1.Items.Add(oSheet.Cells(StartedRow, Startedcolumn).text)
   Next
Next
MessageBox.Show("Successful")
Bharath
  • 72
  • 11
  • Thanks a lot, but how can I display the data in two columns ? This one is being displayed in the same single column. – Wakashio1234 Aug 24 '20 at 11:48
0

The following code shows how to take out the data in Excel and put it into 'List(Of String())', then bind listbox control to the List and draw aligned columns of data in listbox.

Dim XlApp = New Microsoft.Office.Interop.Excel.Application
Dim oBook As Excel.Workbook = XlApp.Workbooks.Open("your file path")
Dim oSheet As Excel.Worksheet = oBook.Worksheets(1)
Dim lst As List(Of String()) = New List(Of String())()
Private RowHeight, RowWidth As Single
Private ColWidths As Single() = Nothing
Private Const RowMargin As Single = 10
Private Const ColumnMargin As Single = 10

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    ListBox1.DrawMode = DrawMode.OwnerDrawVariable
    ListBox1.DataSource = GetList()
End Sub

Private Function GetList() As List(Of String())
    Dim rows As Integer = oSheet.UsedRange.Rows.Count
    'If you want to display only two columns, set the value of 'cols' to 2
    Dim cols As Integer = oSheet.UsedRange.Columns.Count

    For r As Integer = 1 To rows
        Dim Value As String() = New String(cols - 1) {}
        For c As Integer = 1 To cols
            Value(c - 1) = oSheet.Cells(r, c).Text
        Next
        lst.Add(Value)
    Next
    oBook.Close()
    XlApp.Quit()
    Return lst
End Function

Private Sub ListBox1_MeasureItem(sender As Object, e As MeasureItemEventArgs) Handles ListBox1.MeasureItem
    If ColWidths Is Nothing Then
        GetRowColumnSizes(e.Graphics, ListBox1.Font, lst, RowHeight, ColWidths)
        For i As Integer = 0 To ColWidths.Length - 1
            ColWidths(i) += ColumnMargin
        Next

        RowHeight += RowMargin
        RowWidth = ColWidths.Sum()
    End If

    e.ItemHeight = CInt(RowHeight)
    e.ItemWidth = CInt(RowWidth)
End Sub

Private Sub ListBox1_DrawItem(sender As Object, e As DrawItemEventArgs) Handles ListBox1.DrawItem
    Dim values As String() = CType(ListBox1.Items(e.Index), String())
    e.DrawBackground()

    If (e.State And DrawItemState.Selected) = DrawItemState.Selected Then
        DrawRow(e.Graphics, ListBox1.Font, SystemBrushes.HighlightText, Nothing, e.Bounds.X, e.Bounds.Y, RowHeight, ColWidths, values, False)
    Else
        DrawRow(e.Graphics, ListBox1.Font, Brushes.Black, Nothing, e.Bounds.X, e.Bounds.Y, RowHeight, ColWidths, values, False)
    End If
End Sub

Private Sub GetRowColumnSizes(ByVal gr As Graphics, ByVal font As Font, ByVal values As List(Of String()), ByRef max_height As Single, ByRef col_widths As Single())
    Dim num_cols As Integer = values(0).Length
    col_widths = New Single(num_cols - 1) {}
    max_height = 0

    For Each row As String() In values
        For col_num As Integer = 0 To num_cols - 1
            Dim col_size As SizeF = gr.MeasureString(row(col_num), font)
            If col_widths(col_num) < col_size.Width Then col_widths(col_num) = col_size.Width
            If max_height < col_size.Height Then max_height = col_size.Height
        Next
    Next
End Sub

Private Sub DrawRow(ByVal gr As Graphics, ByVal font As Font, ByVal brush As Brush, ByVal box_pen As Pen, ByVal x0 As Single, ByVal y0 As Single, ByVal row_height As Single, ByVal col_widths As Single(), ByVal values As String(), ByVal draw_box As Boolean)
    Dim rect As RectangleF = New RectangleF()
    rect.Height = row_height
    Using sf As StringFormat = New StringFormat()
        Dim x As Single = x0
        For col_num As Integer = 0 To values.Length - 1
            sf.Alignment = StringAlignment.Near
            sf.LineAlignment = StringAlignment.Center
            rect.X = x
            rect.Y = y0
            rect.Width = col_widths(col_num)
            gr.DrawString(values(col_num), font, brush, rect, sf)
            If draw_box Then gr.DrawRectangle(box_pen, rect.X, rect.Y, rect.Width, rect.Height)
            x += col_widths(col_num)
        Next
    End Using
End Sub

Result of my test:

enter image description here

For more details you can see: Make an owner-drawn ListBox that justifies columns in C#

Xingyu Zhao
  • 625
  • 7
  • 27
  • Thanks a lot for your answer, but the task given is that i should use a listbox with formatted zones. Even I find using data grid a better alternative but unfortunately I must use Listbox. – Wakashio1234 Aug 30 '20 at 10:53
  • @Wakashio1234 I have changed my reply, and you can have a look. – Xingyu Zhao Aug 31 '20 at 07:45