我导出表数据到Excel,并试图为它生成的分布图。
用于生成的代码如下,
Dim xlApp As Excel.Application
Dim xlWorkBook As Excel.Workbook
Dim xlWorkSheet As Excel.Worksheet
Dim misValue As Object = System.Reflection.Missing.Value
Dim i As Integer
Dim j As Integer
xlApp = New Excel.ApplicationClass
xlWorkBook = xlApp.Workbooks.Add(misValue)
xlWorkSheet = xlWorkBook.Sheets("sheet1")
For i = 0 To DataGridView2.RowCount - 1
For j = 0 To DataGridView2.ColumnCount - 1
xlWorkSheet.Cells(i + 1, j + 1) = _
DataGridView2(j, i).Value.ToString()
Next
Next
'create chart
Dim chartPage As Excel.Chart
Dim xlCharts As Excel.ChartObjects
Dim myChart As Excel.ChartObject
Dim chartRange As Excel.Range
xlCharts = xlWorkSheet.ChartObjects
myChart = xlCharts.Add(180, 80, 300, 250)
chartPage = myChart.Chart
With chartPage
chartRange = xlWorkSheet.Range("B2", "C16")
.SetSourceData(chartRange)
'set how you want to draw chart i.e column wise or row wise
.PlotBy = Excel.XlRowCol.xlColumns
'set data labels for bars
.ApplyDataLabels(Excel.XlDataLabelsType.xlDataLabelsShowNone)
'set legend to be displayed or not
.HasLegend = True
'set legend location
.Legend.Position = Excel.XlLegendPosition.xlLegendPositionRight
'select chart type
.ChartType = Excel.XlChartType.xlXYScatter
'chart title
.HasTitle = True
.ChartTitle.Text = "XY Scatter Chart"
'set titles for Axis values and categories
Dim xlAxisCategory, xlAxisValue As Excel.Axes
xlAxisCategory = CType(chartPage.Axes(,
_Excel.XlAxisGroup.xlPrimary), Excel.Axes)
xlAxisCategory.Item(Excel.XlAxisType.xlCategory).HasTitle = True
xlAxisCategory.Item(Excel.XlAxisType.xlCategory)
.AxisTitle.Characters.Text = "Title 1"
xlAxisValue = CType(chartPage.Axes(, _Excel.XlAxisGroup.xlPrimary),
Excel.Axes)
xlAxisValue.Item(Excel.XlAxisType.xlValue).HasTitle = True
xlAxisValue.Item(Excel.XlAxisType.xlValue).AxisTitle.Characters.Text
= "Velocity"
End With
xlWorkSheet.SaveAs("C:\vbexcel.xlsx")
xlWorkBook.Close()
xlApp.Quit()
releaseObject(xlApp)
releaseObject(xlWorkBook)
releaseObject(xlWorkSheet)
和它产生后的输出,我得到如下图所示,
但实际的图形看起来像这样如果我在Excel中手动生成图形
我使用Visual Studio 13和框架3.5