Search code examples
excelvb.netnpoi

Exporting three listboxes of different size in the same Excel file


I'm trying to export the content of three different Listboxes, using NPOI package, in three columns of an .xlsx file. While Form10.ListBox1 and Form10.ListBox2 are always made of the same number of elements, Form6.ListBox1 has different size - always smaller than the other two; so, declaring t as size of LB1 and r as size of LB2, I processed the following code:

rowz.CreateCell(0).SetCellValue(ich.CreateRichTextString("Time"))
rowz.CreateCell(1).SetCellValue(ich.CreateRichTextString("HRR"))
rowz.CreateCell(2).SetCellValue(ich.CreateRichTextString("SHRR"))
For i As Integer = 1 To t
    For j As Integer = 1 To r
        Dim row As IRow = worksheet.CreateRow(i)
        row.CreateCell(0).SetCellValue(CDbl(Form10.ListBox1.Items(i - 1)))
        row.CreateCell(1).SetCellValue(CDbl(Form10.ListBox2.Items(i - 1)))
        row.CreateCell(2).SetCellValue(CDbl(Form6.ListBox1.Items(j - 1)))
        rows.Add(row)
    Next j
Next i

My file is exported succesfully but the third column - Form6.ListBox1 one - is exported with only zeros, while the first and the second one are exported properly. Where am I doing wrong at all? Thanks all are gonna answer me. Best regards.


Solution

  • If you keep your way, you will get this : (with 4 for the number of listbox3 elements)

    LB1.value1 - LB2.value1 - LB3.value1

    LB1.value1 - LB2.value1 - LB3.value2

    LB1.value1 - LB2.value1 - LB3.value3

    LB1.value1 - LB2.value1 - LB3.value4

    LB1.value2 - LB2.value2 - LB3.value1

    LB1.value2 - LB2.value2 - LB3.value2

    LB1.value2 - LB2.value2 - LB3.value3

    LB1.value2 - LB2.value2 - LB3.value4

    You have to do it like that :

            rowz.CreateCell(0).SetCellValue(ich.CreateRichTextString("Time"))
            rowz.CreateCell(1).SetCellValue(ich.CreateRichTextString("HRR"))
            rowz.CreateCell(2).SetCellValue(ich.CreateRichTextString("SHRR"))
            For i As Integer = 1 To t
    
                Dim row As IRow = worksheet.CreateRow(i)
                row.CreateCell(0).SetCellValue(CDbl(Form10.ListBox1.Items(i - 1)))
                row.CreateCell(1).SetCellValue(CDbl(Form10.ListBox2.Items(i - 1)))
                If (i <= r) Then
                    row.CreateCell(2).SetCellValue(CDbl(Form6.ListBox1.Items(i - 1)))
                End If
    
                rows.Add(row)
    
            Next i