Reading from Excel getting prompts instead of string on occasion - excel

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

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 Multiple Excel Sheets in a Listview

I am trying to read an excel file that has multiple sheets 1,2,3,4,5,6,7,8,9,10
I need to read several columns of what is in those sheets for example from the range a1: a20 and c1: c20
The result is listing it in a listview, I am trying with several suggestions that appear in the forum, but it only allows me to read one sheet and I need to read several at the same time. Anyway I put the code that I am using.
Thanks in advance
Public Class Frm_ImportarLibro
Public Function Obtenerdatos(ByVal ruta As String, ByVal hoja As String, ByVal rango As String) As DataTable
Dim cadenaConexion As String = "Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties='Excel 8.0;HDR=NO';" &
"Data Source=" & ruta
Using cnn As New OleDbConnection(cadenaConexion)
Dim cmd As OleDbCommand = cnn.CreateCommand()
cmd.CommandText = String.Format("SELECT * FROM [{0}${1}]", hoja, rango)
Dim da As New OleDbDataAdapter(cmd)
Dim dtTemp As New DataTable("Prueba")
da.Fill(dtTemp)
Dim dt As DataTable = dtTemp.Clone()
Dim rows As DataRow() = dtTemp.Select()
For index As Integer = 0 To rows.Count - 1
Dim row As DataRow = rows(index)
If (row.Item(0) Is DBNull.Value) Then
Exit For
End If
dt.ImportRow(row)
Next
Return dt
End Using
End Function
I believe this would be a matter of looping through the sheets and loading a DataTable for each sheet which is then added to a DataSet. My code assumes that the same range is used for each sheet. I made the range contiguous because it would require a separate command for each non-contiguous range. I believe it would be easier to ignore the extraneous data in the resulting DataTable.
Private cadenaConexion As String = "Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties='Excel 8.0;HDR=NO';Data Source="
Private rango As String = "A1:C20"
Private Function GetXLSheetNames(path As String) As List(Of String)
Dim SheetNames As New List(Of String)
Dim dt As DataTable
Using cn As New OleDbConnection(cadenaConexion & path)
cn.Open()
dt = cn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, Nothing)
End Using
For Each row As DataRow In dt.Rows
Dim s = row("Table_Name").ToString
SheetNames.Add(s)
Next
Return SheetNames
End Function
Public Function Obtenerdatos(ByVal ruta As String, ByVal hoja As String, ByVal rango As String) As DataSet
Dim ds As New DataSet
Dim lst = GetXLSheetNames(ruta)
Using cnn As New OleDbConnection(cadenaConexion & ruta),
cmd As New OleDbCommand()
cmd.Connection = cnn
cnn.Open()
For Each s In lst
Dim dt As New DataTable(s)
cmd.CommandText = $"SELECT * FROM [{s}{rango}]"
Using reader = cmd.ExecuteReader
dt.Load(reader)
End Using
ds.Tables.Add(dt)
Next
End Using
Return ds
End Function

Excel Imports way more rows than expected

with my code below I'm importing an excel file that contains 5 worksheets, but I'm only wanting data from 3 of them. I'm getting about 7 times as many rows as expected. How do I ensure I only get populated rows from each sheet? no dupes.
Dim strConnection As String = ConfigurationManager.ConnectionStrings("conn").ToString
Dim excelConnString As String = String.Format("Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" & Server.MapPath(excelFile) & "; Extended Properties=""Excel 12.0 Xml; HDR=Yes""")
Dim conn As OleDbConnection = New OleDbConnection(excelConnString)
Dim cmd As OleDbCommand = New OleDbCommand()
cmd.Connection = conn
Dim da As OleDbDataAdapter = New OleDbDataAdapter(cmd)
Dim dt As DataTable = New DataTable()
conn.Open()
Dim dtSheet As DataTable = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, Nothing)
For Each sheet As System.Data.DataRow In dtSheet.Rows
Dim sheetName As String = sheet("table_name").ToString()
If sheetName = "UT$" Or sheetName = "XRAY$" Or sheetName = "FLANGE$" Then
cmd.CommandText = "select * from [" & sheetName & "] WHERE [Drawing] Is Not NULL"
da.SelectCommand = cmd
da.Fill(dt)
Dim myImportFinding As New ImportFinding
For i As Integer = 0 To dt.Rows.Count - 1
If dt.Rows(i)("Platform") Is Nothing OrElse IsDBNull(dt.Rows(i)("Platform")) Then
myImportFinding.PLATFORM = ""
Else
myImportFinding.PLATFORM = dt.Rows(i)("Platform")
End If
Yes, there was a whole lot of code missing, but the important parts are there. I decided to refactor and have it working now. Each time I looped through it inserted all the rows from the three worksheets. I decided to move the actual import out into a new method and started off with a fresh data table, command and data adapter for each workbook. Seems to work fine now.

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

syntax error on INSERT INTO

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

Resources