在vb.net中的datagridView中的数据透视表

时间:2013-12-12 17:15:48

标签: vb.net

我可以对我遇到的问题使用一些提示,

我有一个包含3列(用户名,时间,事件)的数据表,我从excel文件中提取 我需要计算每个用户的事件数量和花费的时间,并在datagridviewer控件中显示。任何想法都赞赏 这是我的代码的一部分

Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    DateTimePicker1.Format = DateTimePickerFormat.Custom
    DateTimePicker1.CustomFormat = "yyyyMMdd"
    TextBox1.Text = DateTimePicker1.Text
    Using cn As New OleDbConnection With {.ConnectionString = String.Format(ConnectionNoHeader, FileName)}
        cn.Open()
        Dim cmd As OleDbCommand = New OleDbCommand(
            <Text>
                SELECT 
                Log_date,
                   username,
                        event,
                           time,
                             DateDiff('n', Min(time),Max(time)) as Duration
                FROM [<%= SheetName %>$]


WHERE Log_Date = <%= TextBox1.Text %> GROUP BY username
            </Text>.Value,
                cn
        )
        Dim dt As New DataTable
        dt.Load(cmd.ExecuteReader)
        dt.AcceptChanges()
        bsData.DataSource = dt
        DataGridView1.DataSource = bsData
    End Using

结束子

1 个答案:

答案 0 :(得分:0)

我知道这是一个非常老的问题,但是我找到了一个非常简单的解决方案,希望对您有所帮助。这是创建数据透视表并将其显示在DGV中的一种非常简单的方法。 DGV自动创建所有必要的列。抱歉,我没有任何声誉可以发布生成的DGV的图像

  MyDGV.DataSource = GetPivotTable(MySQLcommand)

  Private Function GetPivotTable2(ByVal a_SQLCommand As String) As DataTable

  'Pivot table SQL structure
  'TRANSFORM SUM(ValueField) AS SumOfValueFIeld
  'SELECT RowHeadingField, RowHeadingField, ..., TotalField 
  'FROM TableName
  'WHERE SelectionClause
  'GROUP BY FirstRowField, SecondRowField...
  'PIVOT ColumnHeadingField

  'Example SQL:
  'TRANSFORM SUM(Hours]) AS [SUMHours]
  'SELECT [Member]
  'FROM TimesheetTable
  'WHERE ([Date] >= #7/01/2019# AND [Date] < #7/01/2020#)
  'GROUP BY [Member]
  'PIVOT [Activity]
  ‘This example creates a row for each Member and totals their hours under 
  ‘each activity

  Try

    Dim PivotTable As New DataTable
    Using Connection = New OleDbConnection(MyConnectionString)
      If Connection IsNot Nothing Then
        Dim Expression As New OleDbCommand(a_SQLCommand, Connection)
        Connection.Open()
        Dim da As New OleDbDataAdapter(Expression)
        da.Fill(PivotTable)
      End If
    End Using
    Return PivotTable

  Catch ex As Exception
    MessageBox.Show(ex.Message)
    Return Nothing
  End Try
End Function