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

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

Related

How to make an Excel file a VB.NET resource for dataGridview form?

I’m learning VB.NET, so please forgive my ignorance...
I’m using a dataGridView form to display an Excel file (.xls) as a help file. I use Excel format because it formats very well, can be updated in Excel, and looks great in the dataGridView form...much easier and better than a standard text file.
But even though I can access the file from disk ("C:\DTC.XLS”), I want to place the file inside the VB app itself as a resource. I haven’t been able to do this successfully. I dragged the file into Solution Explorer > My Project > Resources. It shows up as “DTC” under files.
In my code, if I replace the file path (‘C:\DTC.XLS') with the resource handle (My.Resources.DTC), I get an exception: “ System.Data.OleDb.OleDbException: 'Cannot update. Database or object is read-only.’ ”
I’m ok with “read-only”...it’s just a help file. How can I get the dataGridView form to open this resource without exception?
My routine:
Private Sub DTCinfo(sender As Object, e As EventArgs) Handles DTCdataGridView_button.Click
If DTCdataGridView_button.Text = "CLOSE Info" Then
DataGridView1.Hide()
DTCdataGridView_button.Text = "DTC Info"
DTCdataGridView_button.BackColor = SystemColors.ControlDarkDark
Else
DTCdataGridView_button.Text = "CLOSE Info"
DTCdataGridView_button.BackColor = Color.Red
Dim MyConnection As System.Data.OleDb.OleDbConnection
Dim DtSet As System.Data.DataSet
Dim MyCommand As System.Data.OleDb.OleDbDataAdapter
' ***** THE FOLLOWING LINE WORKS OK WITH THIS SUBROUTINE:
' MyConnection = New System.Data.OleDb.OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0;Data Source='c:\DTC.xls';Extended Properties=Excel 8.0;")
' ***** THE FOLLOWING LINE DOES NOT WORK WITH THIS SUBROUTINE (GENERATES AN EXCEPTION):
MyConnection = New System.Data.OleDb.OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0;Data Source=My.Resources.DTC;Extended Properties=Excel 8.0;")
MyCommand = New System.Data.OleDb.OleDbDataAdapter("select * from [Sheet1$]", MyConnection)
MyCommand.TableMappings.Add("Table", "Net-informations.com")
DtSet = New System.Data.DataSet
MyCommand.Fill(DtSet)
DataGridView1.DataSource = DtSet.Tables(0)
DataGridView1.ReadOnly = True
DataGridView1.DefaultCellStyle.WrapMode = DataGridViewTriState.[True]
AutoSizeColumnsMode = True
AutoSizeRowsMode = True
DataGridView1.Columns(0).AutoSizeMode = False
DataGridView1.Columns(0).Width = 50
DataGridView1.Columns(2).Width = 200
DataGridView1.Columns(3).Width = 150
DataGridView1.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells
With DataGridView1
.RowHeadersVisible = False
.Columns(0).HeaderText = "DTC"
.Columns(1).HeaderText = "Test Mode"
.Columns(2).HeaderText = "Description"
.Columns(3).HeaderText = "Action"
End With
MyConnection.Close()
DataGridView1.Show()
End If
End Sub
I found another example of how to do this online. It's simpler to read and easier to understand, but I still get the same exception: "Cannot update: the database or object is read only." How to fix?
' here's another test....
Sub testDataGridView()
Dim dt As New DataTable
' Note, you should use My.Settings rather than My.Resources for storing the data source
' Dim connectionString As String =
' $"provider=Microsoft.Jet.OLEDB.4.0;Data Source={My.Settings.gizmotest};Extended Properties=Excel 8.0;"
Dim connectionString As String =
$"provider=Microsoft.Jet.OLEDB.4.0;Data Source={My.Resources.DTC};Extended Properties=Excel 8.0;"
' Note, you should use import statements for these objects e.g.
' Place this as the first line in the code file
' Imports System.Data.OleDb
Using cn As New OleDbConnection With {.connectionString = connectionString}
Using cmd As New OleDbCommand With {.Connection = cn, .CommandText = "select * from [Sheet1$]"}
Try
cn.Open()
dt.Load(cmd.ExecuteReader)
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Using
End Using
End Sub
OK, seems that the DataGridView form won't work with a read-only source...or at least it won't if it's using the Excel input format...true? And I guess a resource can only be read-only...I guess? I couldn't figure this all out definitively, but it's my best guess...
So I created a temporary file on disk when opening the form, copied the resource to the file, opened the file in the DataGridView form, then closed and deleted the file. Voila! Works. Seems a bit kludgy to me, but hey, it works, looks good, so now on to bigger things....

Importing from non sequential columns in Excel to VB.Net DataGridView using OleDb

I'm trying to import data from a huge excel file to be used in a VB.Net DataGridView.
My problem is that the columns names appear on Row 4 and the columns are not sequential.
Unfortunately editing the Excel database is not an option as many other tools in the organization uses it in its current format.
This is what I've tried so far and i will really appreciate a solution.
Public Sub GetTable()
Dim cmd As System.Data.OleDb.OleDbDataAdapter
Dim ds As New DataSet()
Dim q1, q2, q3, q4, q5, q6 As String
Dim cn As System.Data.OleDb.OleDbConnection
cn = New System.Data.OleDb.OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0;" + "data source=PATH;Extended Properties=Excel 8.0;")
q1 = "select * from [2013$B4:D128]"
'q2 = "select * from [2013$E4:I128]"
'q3 = "select * from [2013$M4:M128]"
'q4 = "select * from [2013$O4:P128]"
'q5 = "select * from [2013$S4:S128]"
'q6 = "select * from [2013$U4:U128]"
cmd = New System.Data.OleDb.OleDbDataAdapter(q1, cn)
cn.Open()
cmd.Fill(ds, "Table1")
cn.Close()
Me.DataGridView1.DataSource = ds
Me.DataGridView1.DataMember = "Table1"
End Sub
I tried using UNION in the query but just received an error from Visual Studio 2013.
Following up from comments above. this is an example using VBA/ADO but illustrates the approach I was suggesting for how to construct your SQL:
Sub Tester()
Dim oConn As New ADODB.Connection
Dim oRS As New ADODB.Recordset
Dim f As ADODB.Field
oConn.Open "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=" & ActiveWorkbook.FullName & _
";Extended Properties='Excel 8.0;HDR=Yes'"
oRS.Open "select * from [Data test$A4:E8] where false", oConn
For Each f In oRS.Fields
Debug.Print f.Name
Next f
oRS.Close
End Sub
If you check the output from your VB.NET version you can choose the field names to include in your select statement.

Vb.Net Windows Form Search Access Database

Ok, hopefully I explain this correctly. I have had about 3 months professional experience working with Access databases, and none with Vb.net, but I am working on a project to get my degree. The goal of this project was to create a Windows Form for my parent's company, All Keyed Up Lock & Safe.
This form was going to link to an Access database with 4 tables that was a listing of some of the company's customers. The form would then allow you to search that database for a specific customer and then return all the information on that specific customer.
This would be useful for billing and also would let us view any special notes we have on the customer before leaving. The four tables are [McDonald's-Corporate Stores], [McDonald's-Independently Owned], [Sonic-Corporate Stores], [Sonic-Independently Owned].
Basically the problem I am having is with the search function. I cannot for the life of me figure out a way to get this to work. I have tried 4 or 5 different solutions and still nothing. I am using Visual Studio 2013. Here is my code I have at the moment, for the search button:
Private Sub SearchButton_Click(sender As Object, e As EventArgs) Handles SearchButton.Click
Dim Connection As New SqlClient.SqlConnectionStringBuilder
Connection.DataSource = "file:///C:\Users\thelukester145\Documents\All%20Keyed%20Up\All%20Keyed%20Up,%20Lock%20&%20Safe,%20LLC.accdb"
Dim objSQLConnection = New SqlClient.SqlConnection(Connection.ConnectionString)
Dim cmd As New SqlCommand()
Dim myTable As New DataTable()
Dim SearchFor = SearchBox.Text
If AddressButton.Checked Then
cmd.Connection = objSQLConnection
cmd.CommandText = "SELECT * FROM [McDonald's-Corporate Stores] WHERE [Address] LIKE '%" & SearchFor & "%'"
Dim myAdapter As New SqlDataAdapter(cmd)
myAdapter.Fill(myTable)
DataGrid.DataGridView1.DataSource = myTable
ElseIf NumberButton.Checked Then
cmd.Connection = objSQLConnection
cmd.CommandText = "SELECT * FROM [McDonald's-Corporate Stores] WHERE [McOpCo#] LIKE '%" & SearchFor & "%'"
Dim myAdapter As New SqlDataAdapter(cmd)
myAdapter.Fill(myTable)
DataGrid.DataGridView1.DataSource = myTable
End If
DataGrid.Show()
End Sub
As you can see I have just been trying to get this to work for just one table and can't even do that. I would prefer not to use the datagrid method to display the information but rather display it in textboxes that are positioned on the form.
Anyways any help would be MUCH appreciated and sorry for such a long question.
Where are you opening the connection. Can you try the following code to establish a connection:
Dim cnnOLEDB As New OleDbConnection
Dim cmdOLEDB As New OleDbCommand
Dim strConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & System.Environment.CurrentDirectory & "\URDataBaseName.mdb"
cnnOLEDB.ConnectionString = strConnectionString
cnnOLEDB.Open()
' your code goes here
cnnOLEDB.Close()

Charting in vb.net form using excel data source

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

Error when trying to read data from Excel in VB.Net

I've tried many different routes in being able to build a page that allows the user to choose an excel file and then reads data from that file. So far all I've gotten is errors.
My latest error is: "Cannot update. Database or object is read-only."
Here is my code:
Protected Sub Upload_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Upload.Click
If (testFile.HasFile) Then
Dim ds As DataSet
Dim strFileType As String = System.IO.Path.GetExtension(testFile.FileName).ToString().ToLower()
Dim MyCommand As System.Data.OleDb.OleDbDataAdapter
Dim MyConnection As System.Data.OleDb.OleDbConnection
MyConnection = New System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & testFile.FileName & ";Extended Properties=""Excel 12.0;HDR=Yes;IMEX=2")
' Select the data from Sheet1 ([in-house$]) of the workbook.
MyCommand = New System.Data.OleDb.OleDbDataAdapter("select * from [Sheet1$]", MyConnection)
ds = New System.Data.DataSet
MyCommand.Fill(ds) - __This is where the error points.__
grvExcelData.DataSource = ds.Tables(0)
End If
End Sub
Any ideas on why this is being thrown? I'm just trying to output the data to a gridview for now. Later I will need to loop through each cell, but I'm trying one step at a time.
Also, if there's a better way to do this I am completely open to it!
Thanks!
But strFileType is the extension of the file that you wish to open. (I.E. for filename.xls it is just the .xls part)
Probably you want the full file name.
MyConnection = New System.Data.OleDb.OleDbConnection( _
"provider=Microsoft.Jet.OLEDB.4.0; " & _
"data source=" & testFile.FileName & "; " & _
"Extended Properties=Excel 8.0")
Now, for the 'better part':
You don't close the connection, and this should never happen.
A simple Using block will save you
Using MyConnection = New OleDbConnection( _
"provider=Microsoft.Jet.OLEDB.4.0; " & _
"data source=" & strFileType & "; " & _
"Extended Properties=Excel 8.0")
' Select the data from Sheet1 ([in-house$]) of the workbook.
Using MyCommand = New OleDbDataAdapter("select * from [Sheet1$]", MyConnection)
Dim ds = New System.Data.DataSet
MyCommand.Fill(ds)
End Using
End Using
And I suggest to add the Import directive to avoid the lenghty namespace prefix for every single OleDb variable