在vb.net中创建具有动态数据范围的Excel图表

时间:2018-06-05 15:01:06

标签: excel vb.net export-to-excel worksheet excel-charts

我正在以实用方式从导出的数据创建Excel饼图和条形图。在这里,我需要动态选择单元格范围。例如,在标题名称之后,应该拾取所有数据,直到单元格包含“TOTAL”行。 以下是我目前的代码。

If String.IsNullOrEmpty(HttpContext.Current.Request.QueryString("oversight")) Then 'This is Summary Level 
        Dim worksheet2 As ExcelWorksheet = pkg.Workbook.Worksheets.Add("Chart - CY Consumable")
        worksheet2.DefaultColWidth = 15

        Dim consumableChart As OfficeOpenXml.Drawing.Chart.ExcelPieChart = worksheet2.Drawings.AddChart("ConsumableChart", OfficeOpenXml.Drawing.Chart.eChartType.Pie)
        Dim r1, r2 As ExcelRange

        r1 = worksheet.Cells("A6:A12") // here I want it to be selected dynamically after header and before the total line
        r2 = worksheet.Cells("B6:B12")
        consumableChart.Series.Add(r2, r1)

        consumableChart.Style = OfficeOpenXml.Drawing.Chart.eChartStyle.Style2
        consumableChart.Title.Text = "FY 2018 Consumable by Regional & Central Oversight Programs"
        consumableChart.Legend.Remove()
        consumableChart.SetPosition(1, 1, 1, 1)
        consumableChart.SetSize(1040, 880)

        consumableChart.DataLabel.ShowLeaderLines = True
        consumableChart.DataLabel.ShowCategory = True
        consumableChart.DataLabel.ShowPercent = True

提前致谢。

1 个答案:

答案 0 :(得分:0)

 Dim totalRow As Integer
    If ds.Tables.Count > 0 Then
        Dim k As Integer = 0
        For j As Integer = 0 To ds.Tables(0).Columns.Count - 1
            If Not skip.Contains(j) Then
                If columnNames.Count > 0 AndAlso columnNames.Count = (ds.Tables(0).Columns.Count - skip.Count) Then
                    strTitle = columnNames(k)
                Else
                    strTitle = ds.Tables(0).Columns(j).ColumnName.Replace("_", " ")
                End If
                worksheet.Cells(p, k + 1).Value = strTitle
                k = k + 1
            End If
        Next
        Dim i As Integer = p + 1
        For Each r As DataRow In ds.Tables(0).Rows
            If includeTotals OrElse (Not r.Item(2).ToString().Trim().ToUpper().StartsWith("TOTAL") AndAlso _
                     Not r.Item(2).ToString().Trim().ToUpper().StartsWith("SUBTOTAL") AndAlso _
                     Not r.Item(2).ToString().Trim().ToUpper().StartsWith("TOTAL") AndAlso _
                     Not r.Item(2).ToString().Trim().ToUpper().StartsWith("SUBTOTAL")) Then

                k = 0
                For j As Integer = 0 To ds.Tables(0).Columns.Count - 1
                    If Not skip.Contains(j) Then
                        If r.Item(j) Is DBNull.Value Then
                            worksheet.Cells(i, k + 1).Value = ""
                        Else
                            If k = 0 Then
                                worksheet.Cells(i, k + 1).Style.Numberformat.Format = "@"
                                worksheet.Cells(i, k + 1).Value = r.Item(j).ToString()
                            Else
                                worksheet.Cells(i, k + 1).Value = r.Item(j)
                            End If
                        End If
                        // Checking if it is first col last row 
                        If r.Item(j).ToString().Contains("TOTAL") Then
                            totalRow = i
                        End If

                        If r.Item(j).GetType().Name = "Decimal" Then
                            If roundUp Then
                                If useParens Then
                                    worksheet.Cells(i, k + 1).StyleID = 2
                                Else
                                    worksheet.Cells(i, k + 1).StyleID = 2 '4
                                End If
                            Else
                                If useParens Then
                                    worksheet.Cells(i, k + 1).StyleID = 1
                                Else
                                    worksheet.Cells(i, k + 1).StyleID = 1 '3
                                End If
                            End If
                        End If
                        k = k + 1
                    End If
                Next
                i = i + 1
            End If
        Next
    End If

    If String.IsNullOrEmpty(HttpContext.Current.Request.QueryString("oversight")) Then 'This is Summary Level 
        Dim worksheet2 As ExcelWorksheet = pkg.Workbook.Worksheets.Add("Chart - CY Consumable")
        worksheet2.DefaultColWidth = 15
 // showing the criteria 
        p = 1
        If includeCriteria Then
            Try
                Dim reportTitle As String = String.Empty

                reportTitle = "Central/Regional Oversight Programs"

                Dim sb As StringBuilder = New StringBuilder()
                sb.Append(reportTitle)
                worksheet2.Cells(p, 1).Value = sb.ToString()
                sb.Length = 0
                p = p + 1

                sb.Append("Budget Fiscal Year : ")
                sb.Append(HttpContext.Current.Session("bfy"))
                worksheet2.Cells(p, 1).Value = sb.ToString()
                sb.Length = 0
                p = p + 1

                sb.Append("Currently viewing transactions from inception through ")
                Dim fm As Integer = CInt(HttpContext.Current.Session("fm"))
                If fm < 4 Then
                    sb.Append(MonthName(fm + 9))
                    sb.Append(" ")
                    sb.Append(CInt(HttpContext.Current.Session("fy")) - 1)
                Else
                    sb.Append(MonthName(fm - 3))
                    sb.Append(" ")
                    sb.Append(HttpContext.Current.Session("fy"))
                End If
                worksheet2.Cells(p, 1).Value = sb.ToString()
                sb.Length = 0
                p = p + 1

                If String.IsNullOrEmpty(HttpContext.Current.Request.QueryString("division")) Then
                    sb.Append("Fund Center(s) :  ALL")
                    worksheet2.Cells(p, 1).Value = sb.ToString()
                    sb.Length = 0
                    p = p + 1
                Else
                    sb.Append("Fund Center(s) : ")
                    sb.Append(HttpContext.Current.Request.QueryString("division"))
                    worksheet2.Cells(p, 1).Value = sb.ToString()
                    sb.Length = 0
                    p = p + 1
                End If

                If String.IsNullOrEmpty(HttpContext.Current.Request.QueryString("fa5")) Then
                    sb.Append("Func Area 5 :  ALL")
                    worksheet2.Cells(p, 1).Value = sb.ToString()
                    sb.Length = 0
                    p = p + 1
                Else
                    sb.Append("Func Area 5 : ")
                    sb.Append(HttpContext.Current.Request.QueryString("fa5"))

                    worksheet2.Cells(p, 1).Value = sb.ToString()
                    sb.Length = 0
                    p = p + 1
                End If

                If Not String.IsNullOrEmpty(HttpContext.Current.Request.QueryString("oversight")) Then
                    sb.Append("Oversight Program - ")
                    sb.Append(HttpContext.Current.Request.QueryString("oversight"))
                    worksheet2.Cells(p, 1).Value = sb.ToString()
                    sb.Length = 0
                    p = p + 1
                End If

                sb.Append("FBMS data as of ")
                sb.Append(HttpContext.Current.Application("lastUpdated_BIA"))
                sb.Append(" at close of business.")
                worksheet2.Cells(p, 1).Value = sb.ToString()
                sb.Length = 0
                p = p + 1

                worksheet2.Cells(p, 1).Value = ""
                p = p + 1
            Catch ex As Exception
                For r As Integer = 1 To p - 1
                    worksheet2.DeleteRow(1, True)
                Next
                p = 1
            End Try
        End If


   //create chart in new tab
        Dim consumableChart As OfficeOpenXml.Drawing.Chart.ExcelPieChart = worksheet2.Drawings.AddChart("ConsumableChart", OfficeOpenXml.Drawing.Chart.eChartType.Pie)
        Dim r1, r2 As ExcelRange
   // setting the value to check the last row
        Dim startColumn As String = "A"
        Dim endColumn As String = "B"
        Dim startIndex As Integer = 8 // Index where to start
        Dim endIndex As Integer = totalRow - 1 'this is determined based on the TOTAL Line from above code

    // checking  and setting  the values and label of pie chart 
        r1 = worksheet.Cells(String.Concat(startColumn, startIndex.ToString(), ":", startColumn, endIndex))
        r2 = worksheet.Cells(String.Concat(endColumn, startIndex.ToString(), ":", endColumn, endIndex))
        consumableChart.Series.Add(r2, r1)

        consumableChart.Style = OfficeOpenXml.Drawing.Chart.eChartStyle.Style2
        consumableChart.Title.Text = "FY 2018 Consumable by Regional & Central Oversight Programs"
        consumableChart.Legend.Remove()
        consumableChart.SetPosition(5, 5, 5, 5)
        consumableChart.SetSize(1040, 880)


        consumableChart.DataLabel.ShowLeaderLines = True
        consumableChart.DataLabel.ShowCategory = True
        consumableChart.DataLabel.ShowPercent = True