vb.net利用listbox控件与excel文件相结合统计数据

  Dim xlApp As Object = Nothing
        Dim xlBooks As Excel.Workbooks = Nothing
        Dim xlBook As Excel.Workbook = Nothing
        Dim xlSheets As Excel.Sheets = Nothing
        Dim xlSheet As Excel.Worksheet = Nothing
        Dim myrange As Excel.Range = Nothing
        Dim i, j As Integer '定义listbox1控件删除重复值变量
        Dim jshe, rows1 As Integer '定义SUMIF计数变量

        Dim strFilePath As String = "C:\Users\Dell\Desktop\数据可视化测试\认统计2020.3.20.xlsx"
        xlApp = New Excel.Application()

        xlBooks = xlApp.Workbooks

        xlBook = xlBooks.Open(strFilePath)
        xlSheets = xlBook.Worksheets
        xlSheet = xlSheets("Sheet1") '这里是你要读入数据的那个sheet页 
        '第一行第一列 
        myrange = xlSheet.Range("h2")
        ' Dim a As String = myrange.Value
        MsgBox(xlSheet.UsedRange.Rows.Count) '最大的使用行数。有记录的总行数。包括写过数据然后删除数据的空白行。要删除这样的行,必须整行删除掉。
        ' MsgBox(xlSheet.UsedRange.Columns.Count) '最大的使用列数。

        TextBox1.Text = myrange.Text
        'MsgBox("暂停")
        ''''''''''''''''''''''''''''''''''''将表格内容填加到Listbox1控件中'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
        For i = 2 To xlSheet.UsedRange.Rows.Count
            If xlSheet.Range("h" & i).Value = Nothing Then '判断如果表格为空数据,停止导出
                Exit For
            End If
            ListBox1.Items.Add(xlSheet.Range("h" & i).Value)
        Next
        '''''''''''''''''''''''''''''''''''将Listbox1控件中重复数据去重''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
        For i = 0 To ListBox1.Items.Count - 1
            For j = ListBox1.Items.Count - 1 To i + 1 Step -1
                If ListBox1.Items(i) = ListBox1.Items(j) Then ListBox1.Items.RemoveAt(j) '使用remove 不能删除
            Next
        Next
        '''''''''''''''''''''''''''''''''''根据listbox控件内容计算数值'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
        rows1 = xlSheet.UsedRange.Rows.Count '表格内所有行数
        jshe = xlSheets.Application.WorksheetFunction.SumIf(xlSheet.Range("h2:h" & rows1), ListBox1.Items.Item(0), xlSheet.Range("d2:d" & rows1)) '求和 参数1:条件序列为H列,参数2:以h2列第一行数据为条件,参数3:在D列中符合条件数据进行相加。
        TextBox1.Text = jshe
        MsgBox(rows1)

        xlBook.Close(True) '关闭工作簿
        xlApp.Quit '结束EXCEL对象

你可能感兴趣的:(vb.net)