1

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

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

谁能告诉我如何使用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
4

2 回答 2

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/

于 2013-08-30T10:53:52.870 回答
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")
于 2013-08-31T07:38:30.683 回答