使用excel数据源以vb.net形式绘制图表

时间:2013-08-30 08:20:21

标签: vb.net excel charts

我有一个表格,其中有一个按钮&图表对象。我有一张excel表,我动态填充。 C& C列D有标题“EOS”&细胞C1和细胞中的“计数”分别为D1。数据填充开始C2& D2直到可变行数。

我想要的是,当点击按钮n表格时,购物车区域会显示一个简单的条形图。图表的X轴应为C2,C3,....,Cn值,Y轴为D2,D3,....,Dn值。我有来自此page的以下代码,它可以满足我的需要,但使用Access数据库作为源代码。

有人可以告诉我如何使用excel sheet作为数据源来实现它吗?

'~~> Code to generate the chart
Private Sub Button2_Click(ByVal sender As System.Object, ByVal _
e As System.EventArgs) Handles Button2.Click
    Dim strConn As String = _
    "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & TextBox1.Text & _
    ";Persist Security Info=False;"

    Dim tblFields As String = "SELECT * from Table1"

    Dim conn As New OleDbConnection(strConn)
    Dim oCmd As New OleDbCommand(tblFields, conn)
    Dim oData As New OleDbDataAdapter(tblFields, conn)
    Dim ds As New DataSet

    conn.Open()
    oData.Fill(ds, "Table1")
    conn.Close()

    Chart1.DataSource = ds.Tables("Table1")
    Dim Series1 As Series = Chart1.Series("Series1")
    Series1.Name = "Sales"
    Chart1.Series(Series1.Name).XValueMember = "nFruits"
    Chart1.Series(Series1.Name).YValueMembers = "nSales"

    Chart1.Size = New System.Drawing.Size(780, 350)
End Sub

2 个答案:

答案 0 :(得分:2)

有很多从Excel中读取的例子

使用VB.NET读取和编写Excel文件 http://www.codeproject.com/Articles/18073/Reading-and-writing-an-Excel-file-using-VB-NET

从Visual Basic .NET中的Excel工作簿中读取数据 http://www.vb-helper.com/howto_net_read_excel.html

VB.NET Excel http://www.dotnetperls.com/excel-vbnet

也是用C#编写的库,用于读取Microsoft Excel文件('97 -2007) http://exceldatareader.codeplex.com/

答案 1 :(得分:1)

我搞定了!错误是因为我没有提供excel文件的绝对路径。这是代码:

Dim strConn As String = _
    "Provider=Microsoft.Jet.OLEDB.4.0;" & _
    "Data Source=C:\Temp\EOS123.xls;Extended Properties=""Excel 8.0;HDR=YES;"""

    Dim tblFields As String = "SELECT EOS, Count from [Sheet1$]"

    Dim conn As New OleDbConnection(strConn)
    Dim oCmd As New OleDbCommand(tblFields, conn)
    Dim oData As New OleDbDataAdapter(tblFields, conn)
    Dim ds As New DataSet

    conn.Open()
    oData.Fill(ds, "Sheet1")
    conn.Close()

    Chart1.DataSource = ds.Tables("Sheet1")