syntax error on INSERT INTO - excel

I had this error by clicking on the save button that saves the 3 textbox in an excel file.
I managed to display the contents of excel file in a datagridview ... but I have not been able to save the data via OleDBCommanBuilder.
it joined the code for any useful purpose:
Imports System
Imports System.Data.OleDb
Public Class Form1
Dim con As OleDbConnection = New OleDbConnection("Provider=Microsoft.Jet.OleDb.4.0; data source=D:\Users\mghazlan\Desktop\doss\DB.xls; Extended Properties=Excel 8.0;")
Dim cmd As OleDbCommand = New OleDbCommand("", con)
Dim da As OleDbDataAdapter = New OleDbDataAdapter()
Dim builder As OleDbCommandBuilder = New OleDbCommandBuilder()
Dim ds As New DataSet()
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
cmd.CommandText = "select * from [Feuil$]"
da = New OleDbDataAdapter(cmd)
builder = New OleDbCommandBuilder(da)
da.Fill(ds, "Feuil")
DataGridView1.DataSource = ds.Tables("Feuil")
' MessageBox.Show(con.State)
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim ligne As DataRow = ds.Tables("Feuil").NewRow
ligne("ID") = TextBox1.Text.ToString
ligne("Nom") = TextBox2.Text.ToString
ligne("Prenom") = TextBox3.Text.ToString
ds.Tables("Feuil").Rows.Add(ligne)
da.Update(ds, "Feuil")
ds.AcceptChanges()
MessageBox.Show("Ajouté avec Succès", "Succès", MessageBoxButtons.OK,
MessageBoxIcon.Information)
End Sub
End Class

Related

Could not find installable ISAM. when taking data from excel sheet

i am trying to get data from excel sheet 2019 using oledb, but when i debug it, it gives me error "Could not find installable ISAM.", should i install something to my pc or is it a code error?
Public Class Form1
Function GetDataFromExcelSheet(ByVal FilePath As String, ByVal sql As String) As DataTable
Dim connection As New OleDb.OleDbConnection
Dim command As New OleDb.OleDbCommand
Dim da As New OleDb.OleDbDataAdapter
Dim dt As New DataTable
connection.ConnectionString = "provider = microsoft.ace.oledb.12.0; data source = " & FilePath & "; Extented Properties=Excel 12.0"
command.Connection = connection
command.CommandText = sql
da.SelectCommand = command
da.Fill(dt)
Return dt
End Function
Private Sub Form1_Shown(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Shown
Dim dt As New DataTable
dt = GetDataFromExcelSheet("C:\Users\User\Desktop\test2145.xlsx", "select distinct class from [Sheet1$]")
Me.ComboBox1.DataSource = dt
Me.ComboBox1.DisplayMember = dt.Columns(0).ToString
Me.ComboBox1.ValueMember = dt.Columns(0).ToString
Me.ComboBox1.SelectedIndex = 1
End Sub
End Class
visual studio says the error is in "da.Fill(dt)"

Read from Excel - write to CSV in different column order

I need to understand if there is a possibility, within VB.NET, to be able to read the columns of an Excel file and write them out to a CSV file in a different order.
In practice, the Excel file we are sent has 6 columns: "amount", "branch", stock "," proposal "," quantity "," type ". The company management system accepts the text file with the columns in a different order: "branch", "stock", "amount", "quantity", "type", "proposal". This creates a problem for me because when I go to convert it my ERP fails to recognize that the column is in a different position.
I arrive at the concrete question, I would like to have the possibility to read the columns and make it possible through a script to be able to position them according to the position I decide.
I tried this code for import and convert to txt, but I need another script:
Imports System.IO
Imports ExcelDataReader
Imports System.Text
Public Class Form1
Dim tables As DataTableCollection
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Using ofd As OpenFileDialog = New OpenFileDialog() With {.Filter = "(*.xls)|*.xls|(*.xls)|*.xlsx"}
If ofd.ShowDialog() = DialogResult.OK Then
txtFileName.Text = ofd.FileName
Using Stream = File.Open(ofd.FileName, FileMode.Open, FileAccess.Read)
Using reader As IExcelDataReader = ExcelReaderFactory.CreateReader(Stream)
Dim result As DataSet = reader.AsDataSet(New ExcelDataSetConfiguration() With {
.ConfigureDataTable = Function(__) New ExcelDataTableConfiguration() With {
.UseHeaderRow = True}})
tables = result.Tables
cboSheet.Items.Clear()
For Each table As DataTable In tables
cboSheet.Items.Add(table.TableName)
Next
End Using
End Using
End If
End Using
End Sub
Private Sub cboSheet_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboSheet.SelectedIndexChanged
Dim dt As DataTable = tables(cboSheet.SelectedItem.ToString())
dgProposte.DataSource = dt
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim writer As TextWriter = New StreamWriter("C:\Users\antonio\Desktop\Prova.txt")
For i As Integer = 0 To dgProposte.Rows.Count - 2 Step +1
For j As Integer = 0 To dgProposte.Columns.Count - 1 Step +1
writer.Write(vbTab & dgProposte.Rows(i).Cells(j).Value.ToString() & vbTab & "")
Next
writer.WriteLine("")
Next
writer.Close()
MessageBox.Show("Dati Esportati")
End Sub
The tables that you get from importing the Excel sheet(s) have their column names set, and you can index the column by its name.
So, and with a little adjustment to factor out some methods:
Imports System.IO
Imports ExcelDataReader
Public Class Form1
Dim tables As DataTableCollection
Private Sub WriteToCsv(tableName As String, filename As String)
Dim columnWriteOrder = {"branch", "stock", "amount", "quantity", "type", "proposal"}
Using writer As TextWriter = New StreamWriter(filename)
Dim tbl = tables(tableName)
For i As Integer = 0 To dgProposte.Rows.Count - 2
Dim vals As New List(Of String)
For j As Integer = 0 To columnWriteOrder.Length - 1
Dim val = tbl.Rows(i).Item(columnWriteOrder(j)).ToString()
vals.Add(val)
Next
writer.WriteLine(String.Join(vbTab, vals))
Next
End Using
End Sub
Private Sub PopulateSheetNames()
cboSheet.Items.Clear()
For Each table As DataTable In tables
cboSheet.Items.Add(table.TableName)
Next
End Sub
Private Sub cboSheet_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboSheet.SelectedIndexChanged
If cboSheet.SelectedIndex >= 0 Then
Dim tableName = cboSheet.SelectedItem.ToString()
Dim dt As DataTable = tables(tableName)
dgProposte.DataSource = dt
End If
End Sub
Private Sub bnLoad_Click(sender As Object, e As EventArgs) Handles bnLoad.Click
Using ofd As OpenFileDialog = New OpenFileDialog() With {.Filter = "(*.xlsx)|*.xlsx|(*.xls)|*.xls", .InitialDirectory = "C:\temp"}
If ofd.ShowDialog() <> DialogResult.OK Then
Exit Sub
End If
txtFileName.Text = ofd.FileName
Using Stream = File.Open(ofd.FileName, FileMode.Open, FileAccess.Read)
Using reader As IExcelDataReader = ExcelReaderFactory.CreateReader(Stream)
Dim edsc = New ExcelDataSetConfiguration() With {
.ConfigureDataTable = Function(__) New ExcelDataTableConfiguration() With {
.UseHeaderRow = True}}
Dim result As DataSet = reader.AsDataSet(edsc)
tables = result.Tables
End Using
End Using
PopulateSheetNames()
End Using
End Sub
Private Sub bnSaveAsCsv_Click(sender As Object, e As EventArgs) Handles bnSaveAsCsv.Click
If cboSheet.SelectedIndex < 0 Then
MessageBox.Show("Please select a sheet name.", "No sheet name selected", MessageBoxButtons.OK, MessageBoxIcon.Information)
Exit Sub
End If
Dim sheetName = cboSheet.SelectedItem.ToString()
If Not String.IsNullOrEmpty(sheetName) Then
WriteToCsv(sheetName, "C:\temp\Prova.csv")
MessageBox.Show("Dati Esportati.", "Dati Esportati", MessageBoxButtons.OK, MessageBoxIcon.Information)
End If
End Sub
End Class
I changed the names of the buttons because "Button1" and "Button2" are not descriptive.
(I set the .InitialDirectory of the OpenFileDialog because it was convenient for me.)
Why you don't map a DTO of your data table?
Public Class MioDto
Property campoUno As String
Property campoDue As String
'...ecc
End Class
and then you can fill a dto in a cicle or so...
Dim a As New MioDto() With {.campoUno="...", campoDue="..."}
or if you want you can use
https://github.com/AutoMapper/AutoMapper
When you have a Dto class filled you can use it for generate your txt with youor preferred order.

Reading from Excel getting prompts instead of string on occasion

The issue i am having right now is that the first row of the data i get from the excel documents sometimes come back as prompts instead of their proper data types(only some of the cells). i have tried remaking the spreadsheets and redoing all the formatting on the excel side so i'm left to assume its something to do with the oledb class? Any information or a push in the right direction would be greatly appreciated.
Imports Microsoft.Office.Interop
Public Class Form1
Dim ExTable1 As New DataTable
Dim ExTable2 As New DataTable
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
OpenFileDialog1.ShowDialog()
ExTable1 = ConnectToFile(OpenFileDialog1.FileName)
Table1.DataSource = ExTable1
End Sub
Function ConnectToFile(path)
Dim dt As DataTable = New DataTable
Dim selStr As String = "SELECT * FROM [{0}]"
Dim dtSchema
Dim drSchema
Dim con As OleDb.OleDbConnection = New OleDb.OleDbConnection
con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & path & ";Extended Properties=Excel 12.0 Xml;"
con.Open()
dtSchema = con.GetOleDbSchemaTable(OleDb.OleDbSchemaGuid.Tables, New Object() {Nothing, Nothing, Nothing, "TABLE"})
drSchema = dtSchema.Rows(0)
Dim Sheet1 = drSchema("TABLE_NAME")
Dim cmd As OleDb.OleDbCommand = New OleDb.OleDbCommand(String.Format(selStr, Sheet1))
cmd.Connection = con
Dim da As OleDb.OleDbDataAdapter = New OleDb.OleDbDataAdapter
da.SelectCommand = cmd
da.Fill(dt)
Table1.DataSource = dt
con.Close()
con.Dispose()
Return dt
End Function
End Class

My VB.net Code is working but it's displaying errors afterwards

I've written some code in vb.net that adds, deletes and updates a spreadsheet. The add and the delete button works excellently without bring up any errors. But the update button works but it brings an error afterwards. Can someone help me know what's the problem and help me fix it? Any help will be appreciated.
Imports System.Data.OleDb
Imports System.IO
Imports System.Data.DataTable
Imports Microsoft.Office.Interop
Public Class Welcome
Private Sub ImportExceldata(DataExcelFile As String, ImportData As DataGridView)
If ComboBox1.SelectedIndex.Equals(0) Then
Try
Dim MyConnection As System.Data.OleDb.OleDbConnection
Dim dataSet As System.Data.DataSet
Dim MyCommand As System.Data.OleDb.OleDbDataAdapter
MyConnection = New System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" & DataExcelFile & "';Extended Properties=Excel 8.0;")
MyCommand = New System.Data.OleDb.OleDbDataAdapter("SELECT * FROM [CandidatesCallCenterLocation$]", MyConnection)
'MyCommand.TableMappings.Add("Table", "Attendace")
dataSet = New System.Data.DataSet
MyCommand.Fill(dataSet)
ImportData.DataSource = dataSet.Tables(0)
DataGridView.DataSource = dataSet.Tables(0)
MyConnection.Close()
Catch ex As Exception
MsgBox(ex.Message.ToString)
End Try
ElseIf ComboBox1.SelectedIndex.Equals(1) Then
Try
Dim MyConnection As System.Data.OleDb.OleDbConnection
Dim dataSet As System.Data.DataSet
Dim MyCommand As System.Data.OleDb.OleDbDataAdapter
MyConnection = New System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" & DataExcelFile & "';Extended Properties=Excel 8.0;")
MyCommand = New System.Data.OleDb.OleDbDataAdapter("SELECT * FROM [ExpectedNumberofCalls$]", MyConnection)
'MyCommand.TableMappings.Add("Table", "Attendace")
dataSet = New System.Data.DataSet
MyCommand.Fill(dataSet)
ImportData.DataSource = dataSet.Tables(0)
DataGridView.DataSource = dataSet.Tables(0)
MyConnection.Close()
Catch ex As Exception
MsgBox(ex.Message.ToString)
End Try
ElseIf ComboBox1.SelectedIndex.Equals(2) Then
Try
Dim MyConnection As System.Data.OleDb.OleDbConnection
Dim dataSet As System.Data.DataSet
Dim MyCommand As System.Data.OleDb.OleDbDataAdapter
MyConnection = New System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" & DataExcelFile & "';Extended Properties=Excel 8.0;")
MyCommand = New System.Data.OleDb.OleDbDataAdapter("SELECT * FROM [CostProcessingTelephoneCalls$]", MyConnection)
'MyCommand.TableMappings.Add("Table", "Attendace")
dataSet = New System.Data.DataSet
MyCommand.Fill(dataSet)
ImportData.DataSource = dataSet.Tables(0)
DataGridView.DataSource = dataSet.Tables(0)
MyConnection.Close()
Catch ex As Exception
MsgBox(ex.Message.ToString)
End Try
End If
End Sub
Private Sub ComboBox_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged
ImportExceldata("C:\Users\Home\Desktop\dss.xlsx", DataGridView)
End Sub
The above code imports the spreadsheets to the DatagridView.It works fine. I haven't encountered any problems so far here.
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
For Each row As DataGridViewRow In DataGridView.SelectedRows
DataGridView.Rows.Remove(row)
Next
End Sub
The code above deletes rows in the spreadsheet. No problems have been encountered so far.
Private Sub Button1_Click_1(sender As Object, e As EventArgs) Handles Button1.Click
If ComboBox1.SelectedIndex.Equals(0) Then
Try
Dim x As Integer
DataGridView.Rows.Item(x).Cells(0).Value = ACTextBox.Text
DataGridView.Rows.Item(x).Cells(1).Value = MATextBox.Text
DataGridView.Rows.Item(x).Cells(2).Value = AFCTextBox.Text
DataGridView.Rows.Item(x).Cells(3).Value = TextBoxWPH.Text
Catch ex As Exception
MsgBox(ex.Message.ToString)
End Try
End If
If ComboBox1.SelectedIndex.Equals(1) Then
Try
Dim a As Integer
DataGridView.Rows.Item(a).Cells(0).Value = ACTextBox.Text
DataGridView.Rows.Item(a).Cells(1).Value = RegionTextBox.Text
DataGridView.Rows.Item(a).Cells(2).Value = ENCTextBox.Text
Catch ex As Exception
MsgBox(ex.Message.ToString)
End Try
End If
If ComboBox1.SelectedIndex.Equals(2) Then
Try
Dim b As Integer
DataGridView.Rows.Item(b).Cells(0).Value = ACTextBox.Text
DataGridView.Rows.Item(b).Cells(1).Value = RegionTextBox.Text
DataGridView.Rows.Item(b).Cells(2).Value = ENCTextBox.Text
Catch ex As Exception
MsgBox(ex.Message.ToString)
End Try
End If
End Sub
The code above adds data to any column that you want to add data to. But the only situation here is that the add button replaces the whole row instead of adding a new row to the spreadsheet. But it cause any problems.Otherwise there are no more problems that I've encountered so far.
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Dim AreaCode, MetropolitanArea As String
Dim AnnualFixedArea, WagePerHour As Integer
Dim x As Integer
MsgBox("Do you want to update the records?")
If ComboBox1.SelectedIndex.Equals(0) Then
Try
AreaCode = ACTextBox.Text
DataGridView.Rows.Item(x).Cells(0).Value = ACTextBox.Text
MetropolitanArea = MATextBox.Text
DataGridView.Rows.Item(x).Cells(1).Value = MATextBox.Text
AnnualFixedArea = AFCTextBox.Text
DataGridView.Rows.Item(x).Cells(2).Value = AFCTextBox.Text
WagePerHour = TextBoxWPH.Text
DataGridView.Rows.Item(x).Cells(3).Value = TextBoxWPH.Text
Catch ex As Exception
MsgBox(ex.Message.ToString)
End Try
End If
If ComboBox1.SelectedIndex.Equals(1) Then
Try
Catch ex As Exception
End Try
End If
End Sub
End Class
This is where the error is displaying after I update the columns. Only the part where AreaCode = ACTextBox.Text works. The other textbox work but after I click the update button, it displays the following errors.
https://ibb.co/JdzGmfp
https://ibb.co/QmnwJZr
Thanks

Retrive the rows/data from datagridview after the application has been closed

I have a dialog form here where a user can upload a file from Excel and import and display to the datagrid view. However, my problem is when the user closes the application or form, the datagridview was empty and reset.
My question is how can I retrieve its data and display it, every time the user will open the form. Is it possible if the data was not saved in the database and will only based on the uploaded or imported Excel file? And if the user has uploaded a new Excel, I want to replace the existing rows or data in the datagridview.
I really hope you would help.
Below you can find my code:
Imports System.Data
Public Class frmSupplier
Private Sub btn_upload_supplier_Click(sender As Object, e As EventArgs) Handles btn_upload_supplier.Click
Try
If btn_upload_supplier.Text = "New" Then
Dim Openfile As New OpenFileDialog
Openfile.ShowDialog()
txtpath_supplier.Text = Openfile.FileName
Label1.Text = txtpath_supplier.Text
If txtpath_supplier.Text = Nothing Then
Else
btn_upload_supplier.Text = "Upload"
End If
ElseIf btn_upload_supplier.Text = "Upload" Then
Dim dtItemlist As New DataTable
Dim obj As New Basegeneral
Try
Dim MyConnection As System.Data.OleDb.OleDbConnection
Dim DtSet As System.Data.DataSet
Dim MyCommand As System.Data.OleDb.OleDbDataAdapter
MyConnection = New System.Data.OleDb.OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + txtpath_supplier.Text.ToString() + "; Extended Properties=Excel 8.0;")
MyCommand = New System.Data.OleDb.OleDbDataAdapter("select * from [Sheet1$]", MyConnection)
MyCommand.TableMappings.Add("Table", "TestTable")
DtSet = New System.Data.DataSet
MyCommand.Fill(DtSet)
dg_details.DataSource = DtSet.Tables(0)
MyConnection.Close()
Catch ex As Exception
MessageBox.Show(Me, ex.ToString, "Error:")
End Try
End If
Catch ex As Exception
MessageBox.Show(Me, ex.ToString, "Error:")
End Try
End Sub
Private Sub btnDelete_Click(sender As Object, e As EventArgs) Handles btnDelete.Click
Try
Dim row As System.Data.DataRow = GridView1.GetDataRow(GridView1.FocusedRowHandle)
If row.Item(0).ToString = "" Then
MessageBox.Show("Please select supplier to remove", "KCC Retail System")
Return
End If
If DevExpress.XtraEditors.XtraMessageBox.Show("Are you sure you want to remove supplier '" & row.Item(0) & "'?", "WARNING", MessageBoxButtons.YesNo, MessageBoxIcon.Error, MessageBoxDefaultButton.Button2) = Windows.Forms.DialogResult.Yes Then
MessageBox.Show("Supplier " & row.Item(0) & " has been removed!", "KCC Retail System")
GridView1.DeleteRow(GridView1.FocusedRowHandle)
Else
Return
End If
Catch ex As Exception
MessageBox.Show(ex.Message, "Error :")
End Try
End Sub
Private Sub btn_clear_Click(sender As Object, e As EventArgs) Handles btn_clear.Click
btn_upload_supplier.Text = "New"
txtpath_supplier.Text = ""
End Sub
The form will be open when the user click the button and it will display as a dialog (ShowDialog).
To save and then re-hydrate the contents of a DataGridView you can use a binary formatter.
Imports System.IO
Import System.Runtime.Serialization.Formatters.Binary
Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
Dim FileName As String = "MyData.dat" 'Will save in bin directory
Dim dt As DataTable = CType(DataGridView1.DataSource, DataTable)
' 1. Create an instance of a Binary Formatter
Dim bf As New BinaryFormatter
' 2. Create a file stream passing in (the name of the file to create, mode: Create, access: Write, share: none)
Using fs As Stream = New FileStream(FileName, FileMode.Create, FileAccess.Write, FileShare.None)
' 3. use the Serialize method of the Binary Formatter passing in the file stream(file name, create, write, no share) And the object
bf.Serialize(fs, dt)
End Using
End Sub
Private Sub btnFillFromFill_Click(sender As Object, e As EventArgs) Handles btnFillFromFill.Click
Dim FileName As String = "MyData.dat"
Dim dt As DataTable
' 1. Create an instance of Binary Formatter
Dim bf As New BinaryFormatter()
' 2. Get an instance of a FileStream for the OpenRead method of File passing in (the fileName)
Using fs As Stream = File.OpenRead(FileName)
' 3. cast back to original object, the Deserialize method of the Binary Formatter passing in the File Stream
dt = CType(bf.Deserialize(fs), DataTable)
End Using
DataGridView1.DataSource = dt
End Sub

Resources