Reputation: 290
I have a form in which there is a button & chart object. I have an excel sheet which I am populating dynamically. Columns C & D have headers "EOS" & "Count" in cells C1 & D1 respectively. The data filling starts C2 & D2 onwards till variable number of rows.
What I want is, when the button n form is clicked, a simple bar chart is displayed in the cart area. the chart should have X-axis as C2, C3, ....,Cn values and Y-axis as D2, D3, ....,Dn values. I have the following code from this page that does what I need but uses an Access db as source.
Can anyone please show me how to achieve it using excel sheet
as data source?
'~~> 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
Upvotes: 1
Views: 4908
Reputation: 290
I got it working ! The error was because I was not supplying absolute path of the excel file. Here is the code:
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")
Upvotes: 1
Reputation: 2809
There are many examples of reading from Excel
Reading and writing an Excel file using VB.NET http://www.codeproject.com/Articles/18073/Reading-and-writing-an-Excel-file-using-VB-NET
Read data from an Excel workbook in Visual Basic .NET http://www.vb-helper.com/howto_net_read_excel.html
VB.NET Excel http://www.dotnetperls.com/excel-vbnet
Also library written in C# for reading Microsoft Excel files ('97-2007) http://exceldatareader.codeplex.com/
Upvotes: 2