Charting in vb.net form using excel data source - vb.net

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

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/

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")

Related

Import spread sheet (OpenOffice) to Visual Basic .net combo box

I have a list of client names, project names, employee names, and hourly rates in an OpenOffice spreadsheet that I need to import to Visual Basic .net 2017. It would be preferred if I could do this to a combo box, so the user can just select the names from a drop-down list. It seems as if this is impossible without setting up an SQL server. Does anyone know how I should go about doing this?
I've tried this but it says that it can't connect to Microsoft.Ace.OLEDB.12.0
I got this code from a YouTube video
Private Sub btnGetSpread_Click(sender As Object, e As EventArgs) Handles btnGetSpread.Click
Try
Dim MyConnection As System.Data.OleDb.OleDbConnection
Dim dataSet As System.Data.DataSet
Dim MyCommand As System.Data.OleDb.OleDbDataAdapter
Dim path As String = "P:\Coding\Visual Studio\Visual Basic\TestProject\TestProject\bin\Files\Company_Sheet.ods"
MyConnection = New System.Data.OleDb.OleDbConnection("Provider=Microsoft.Ace.OLEDB.12.0;Data Source =" + "P:\Coding\Visual Studio\Visual Basic\TestProject\TestProject\bin\Files\Company_Sheet.ods" + ";Extended Properties=Excel 12.0;")
MyCommand = New System.Data.OleDb.OleDbDataAdapter("select * from [Sheet1$]", MyConnection)
dataSet = New System.Data.DataSet
MyCommand.Fill(dataSet)
dgvSpread.DataSource = dataSet.Tables(0)
MyConnection.Close()
Catch ex As Exception
MsgBox(ex.Message.ToString)
End Try
End Sub
This will get you started. I sometimes have to import data from Excel spreadsheets into an Oracle database, this code is years old, but still works (VS 2013). Modify to suit your situation.
Dim sourceFile As String = "C:\Users\appdata\Documents\SomeData.xls"
Dim srcConnString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & sourceFile & ";Extended Properties=""Excel 8.0;HDR=YES;"""
Dim srcConn As OleDbConnection = New OleDbConnection(srcConnString)
srcConn.Open()
' in the select statement, the fields are the column names in the spreadsheet and are expected to be in row 1 and are case sensitive
' the from clause in the query is the tab of the spreadsheet where the data is
Dim cmdExcel As OleDbCommand = New OleDbCommand("Select NAME,ADDRESS,CITY,STATE,ZIP From [DATA$] Where some where clause", srcConn)
Dim drExcel As OleDbDataReader = cmdExcel.ExecuteReader()
' Now loop through the rows in the spreadsheet
While drExcel.Read()
'Do stuff ...
End While

Set datasource of datagridview in module

I am writing a program that will automatically process files, based on a set of criteria. In order to process these, I need to load the Excel file first, before I can process it.
I create a module called "NewBusAuto". In here, I created a new datagridview. I am trying to set the datasource of this, but whenever I do, it doesn't actually bind. When I try and process each row/column, it is saying it is still empty.
Code used:
Module m_NewBusinessAutomation
Dim dgvImport As DataGridView
Public Sub NewBusAuto(ByVal folderName As String,
ByVal fileName As String,
ByVal executeScript As String)
dgvImport = New DataGridView
If Path.GetExtension(fileName) = ".xls" Or Path.GetExtension(fileName) = ".xlsx" Then
Using cn As New System.Data.OleDb.OleDbConnection
Dim builder As New OleDbConnectionStringBuilder With _
{.DataSource = folderName & "\" & fileName,
.Provider = "Microsoft.ACE.OLEDB.12.0"}
builder.Add("Extended Properties", "Excel 12.0; IMEX=1;HDR=Yes;")
cn.ConnectionString = builder.ConnectionString
cn.Open()
Using cmd As OleDbCommand = New OleDbCommand With {.Connection = cn}
cmd.CommandText = "SELECT * FROM [Sheet1$]"
Dim dr As System.Data.IDataReader = cmd.ExecuteReader
Dim dt As New DataTable
dt.Load(dr)
dgvImport.DataSource = dt
dgvImport.Refresh()
Messagebox.show(dgvImport.RowCount & "-" & dgvImport.ColumnCount)
dr.Close()
End Using
End Using
End If
The messagebox is giving me "0 - 0" as a result.
I need to load the Excel file to the actual database. Any help would be appreciated!

How do I filter multiple columns in datagridview exported from excel in VB.NET

I have a datagridview which i import an excel file.my excel columns are name,id,sex,grade,seat no .what i want is filter all the columns (multi column filter) in the datagridview except name and id via a textbox. i.e. when i type a single word in the text box i want it to filter the columns of sex,grade and seat no at the same time.
here is the excel importing code to the datagridview....
Private Sub OpenFileDialog1_FileOk(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles OpenFileDialog1.FileOk
Dim filePath As String = OpenFileDialog1.FileName
Dim extension As String =
Path.GetExtension(filePath)
Dim header As String = If(rbHeaderYes.Checked, "YES", "NO")
Dim conStr As String, sheetName As String
conStr = String.Empty
Select Case extension
Case ".xls"
'Excel 97-03
conStr = String.Format(Excel03ConString, filePath, header)
Exit Select
Case ".xlsx"
'Excel 07
conStr = String.Format(Excel07ConString, filePath, header)
Exit Select
End Select
'Get the name of the First Sheet.
Using con As New OleDbConnection(conStr)
Using cmd As New OleDbCommand()
cmd.Connection = con
con.Open()
Dim dtExcelSchema As DataTable = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, Nothing)
sheetName = dtExcelSchema.Rows(0)("TABLE_NAME").ToString()
con.Close()
End Using
End Using
'Read Data from the First Sheet.
Using con As New OleDbConnection(conStr)
Using cmd As New OleDbCommand()
Using oda As New OleDbDataAdapter()
Dim dt As New DataTable()
cmd.CommandText = (Convert.ToString("SELECT * From [") & sheetName) + "]"
cmd.Connection = con
con.Open()
oda.SelectCommand = cmd
oda.Fill(dt)
con.Close()
'Populate DataGridView.
DataGridView1.DataSource = dt
End Using
End Using
End Using
End Sub
You should bind your DataTable to a BindingSource, which you would add in the designer, and then bind that to the grid. You can then filter the data by setting the Filter property of the BindingSource. It's basically a SQL WHERE clause so, just like in SQL, you can use AND and OR operators to combine multiple criteria, e.g.
myBindingSource.Filter = String.Format("Column1 LIKE '%{0}%' OR Column2 LIKE '%{0}%'", myTextBox.Text)
Just note that you can only use LIKE for text columns, not numbers or dates or anything else.

Getting data from an Excel datatable using OLEDB

I have an excel 2007 xlsm file, where on one of the tabs I have several data tables. Using VB.NET, I'm trying to read one table at a time as a named range like so:
Public Function OpeDataFromRange(ByVal Filename as string, ByVal RangeName As String, ByVal bColumnNames As Boolean) as DataTable
' Returns a DataSet containing information from a named range
' in the passed Excel worksheet
Dim sHDR As String
Dim strConn As String
If bColumnNames Then
sHDR = "Yes"
Else
sHDR = "No"
End If
strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=" & Filename & ";Extended Properties=""Excel 12.0 Macro;HDR=" & sHDR & """;"
Dim objConn _
As New System.Data.OleDb.OleDbConnection(strConn)
objConn.Open()
' Create objects ready to grab data
Dim objCmd As New System.Data.OleDb.OleDbCommand( _
"SELECT * FROM [" & RangeName & "]", objConn)
Dim objDA As New System.Data.OleDb.OleDbDataAdapter()
objDA.SelectCommand = objCmd
' Fill DataSet
Dim objDS As New System.Data.DataSet()
objDA.Fill(objDS)
' Clean up and return DataSet
objConn.Close()
return objDS
End Function
But I'm getting the error at Fill command:
The Microsoft Office Access database engine could not find the object 'MyNamedTable1'. Make sure the object exists and that you spell its name and the path name correctly.
I tried to read the entire sheet in the SELECT, and then to fish out my table through objDS.Tables, but then Tables gets loaded with only one table with everything in it.
Any Recommendations?
You cannot use Microsoft.Jet.OLEDB.4.0 with Excel 12.0 you should use Microsoft.ACE.OLEDB.12.0 instead.
Incidentally, you are filling a DataSet but returning a DataTable you need to change one of those.
Personally I prefer to use a DataTable for this but you may prefer a DataSet. If you want to use a DataTable you can...
Dim objDT As New DataTable
objDT.Load(objCmd.ExecuteReader)

how to add new column to a database after importing data from xl sheet

I need to import data of a xl sheet to a database and while it is being saved in db i need to add another column to it and save it. I am using following code:-------
Private Sub cmdImport_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdImport.Click
Dim _filename As String = txtFile.Text
'Create connection object for xl sheet
Dim _conn As String
_conn = "Provider=Microsoft.ACE.OLEDB.12.0;" & "Data Source=" & _filename & ";" & "Extended Properties=Excel 8.0;"
Dim _connection As OleDb.OleDbConnection = New OleDb.OleDbConnection(_conn)
'List columns you need from the Excel file
Dim _command As New System.Data.OleDb.OleDbCommand("Select * FROM [Sheet1$]", _connection)
'open connection for xl sheet
_connection.Open()
' Create DbDataReader to read Data from xl sheet
Dim dr As System.Data.OleDb.OleDbDataReader = _command.ExecuteReader()
'open connection for database to write into it
cnnOLEDB.Open()
Dim chal_no As String
Try
'reading data from xl sheet utill the last rows
If dr.HasRows() Then
While dr.Read()
'writing the read data from xl sheet into access database
chalan_no = cmbChal_noImport.Text
'getting the parameter values from xl sheet to write into access db
Dim P1 As New OleDb.OleDbParameter
P1.DbType = DbType.String
P1.ParameterName = "sr_no"
P1.Value = dr.GetValue(0)
'adding the parameters in to the db
Dim strSql As String = "INSERT INTO Vendor_Machine(sr_no,chalan_no) VALUES (#srno,#chalan_no)"
Dim cmd As OleDb.OleDbCommand = New OleDb.OleDbCommand(strSql, cnnOLEDB)
cmd.Parameters.AddRange(New OleDb.OleDbParameter() {P1})
cmd.Parameters.AddWithValue("#srno", DbType.String)
cmd.Parameters.AddWithValue("#chalan_no", chalan_no)
cmd.ExecuteScalar()
End While
End If
MsgBox("Xl sheet Import Complete", MsgBoxStyle.OkOnly)
Catch ex As Exception
MsgBox(ex.Message)
Exit Sub
Finally
'closing the access and xl sheet connection
cnnOLEDB.Close()
_connection.Close()
End Try
'End Using
End Sub
Problem is that, it doesn't show any error but after saving the data in db , in chalan_no column it shows a constant"16". plz resolve my problem..
Thank you.
I am not sure if this code will solve your problem. But this is bit simpler than yours.
Private Sub cmdImport_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdImport.Click
Dim _filename As String = txtFile.Text
'Create connection object for xl sheet
Dim _conn As String
_conn = "Provider=Microsoft.ACE.OLEDB.12.0;" & "Data Source=" & _filename & ";" & "Extended Properties=Excel 8.0;"
Dim _connection As OleDb.OleDbConnection = New OleDb.OleDbConnection(_conn)
'List columns you need from the Excel file
Dim _command As New System.Data.OleDb.OleDbCommand("Select * FROM [Sheet1$]", _connection)
'open connection for xl sheet
_connection.Open()
' Create DbDataReader to read Data from xl sheet
Dim dr As System.Data.OleDb.OleDbDataReader = _command.ExecuteReader()
'open connection for database to write into it
cnnOLEDB.Open()
Dim chal_no As String
Try
'reading data from xl sheet utill the last rows
If dr.HasRows() Then
While dr.Read()
'writing the read data from xl sheet into access database
chalan_no = cmbChal_noImport.Text
'getting the parameter values from xl sheet to write into access db
Dim P1 As New OleDb.OleDbParameter
'P1.DbType = DbType.String
'P1.ParameterName = "sr_no"
'P1.Value = dr.GetValue(0)
'adding the parameters in to the db
Dim strSql As String = "INSERT INTO Vendor_Machine(sr_no,chalan_no) VALUES (?,?)"
Dim cmd As OleDb.OleDbCommand = New OleDb.OleDbCommand(strSql, cnnOLEDB)
cmd.CommandType = CommandType.Text
With cmd.Parameters
.Add("#p1", OleDbType.VarChar).Value = dr.GetValue(0)
.Add("#p2", OleDbType.VarChar).Value = cmbChal_noImport.Text
End With
' cmd.Parameters.AddRange(New OleDb.OleDbParameter() {P1})
'cmd.Parameters.AddWithValue("#srno", DbType.String)
'cmd.Parameters.AddWithValue("#chalan_no", chalan_no)
cmd.ExecuteNonQuery()
'cmd.ExecuteScalar()
End While
End If
MsgBox("Xl sheet Import Complete", MsgBoxStyle.OkOnly)
Catch ex As Exception
MsgBox(ex.Message)
Exit Sub
Finally
'closing the access and xl sheet connection
cnnOLEDB.Close()
_connection.Close()
End Try
'End Using
End Sub