How to use ACE OLEDB to import Excel data into VB? - vb.net

Originally I was using Office Interop to import data, but that was a headache and a half for both me and my computer. Right now I'm attempting to load it with ACE, but my data grid isn't being populated. Once that's up and running I need to know how to use that data in other ways, and how to grab specific cells of data from that DataSet. I'm using Visual Studio 2008, by the way.
Right now I have...
Public Function funcUpdate(ByVal sFileLoc As String) As Boolean
'Determine connection string properties
Dim dbProperty As String
If updFileExt = ".xlsx" Then
dbProperty = "Excel 12.0 Xml;HDR=No"
ElseIf updFileExt = ".xls" Then
dbProperty = "Excel 12.0;HDR=No"
Else
MessageBox.Show("FATAL: File type error on updater", "OHGAWDNO", MessageBoxButtons.OK, MessageBoxIcon.Error)
updateTerm()
Return False
End If
Dim dbConn As New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & updFile & ";Extended Properties=" & dbProperty & ";")
Dim dbCommand As New OleDb.OleDbDataAdapter("select * from [sheet1$]", dbConn)
Dim dtSet As New DataSet
Try
dbCommand.TableMappings.Add("Table", "ExcelTest")
dbCommand.Fill(dtSet)
Form1.DataGrid1.DataSource = dtSet.Tables(0)
Catch exlErr As Exception
Finally
dbConn.Close()
End Try
updateTerm()
End Function

Try to do this.
Dim path As String = "c:\example.xlsx"
Dim constr As String = [String].Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=""Excel 12.0 Xml;" & _
"HDR=YES;IMEX=1;""", path)
Dim adapter As New OleDbDataAdapter
Using cn As New System.Data.OleDb.OleDbConnection(constr)
Try
cmdselcet = New OleDbCommand("SELECT * FROM [Sheet1$]", cn)
cn.Open()
adapter.SelectCommand = cmdselcet
Dim ds As DataSet
ds = New DataSet
'Display
adapter.Fill(ds)
DataGridView1.DataSource = ds.Tables(0)
MsgBox("Done!")
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Using

Related

Why is my VB program throwing an exception complaining that a OleDbDataReader is closed, when it should absolutely be open?

I am trying to use OleDB and SQLBulkCopy to pull data off an excel spreadsheet, into an SQL database. When I try and run my code, I get the following exception, triggered by
"bulkCopy.WriteToServer(objDR)" (which is also described in the question title): exception data
OleDB successfully reads the excel sheet which is then populated properly in the DataGridView I created within a WinForm for debugging purposes.
Below is a snippet of the relevant code.
Dim ExcelConnection As New System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\\damon\Everyone\sheet1erictest.xlsx;Extended Properties=""Excel 12.0 Xml;HDR=Yes""")
ExcelConnection.Open()
Dim sheet As String = "Sheet5$"
Dim expr As String = "SELECT * FROM [" + sheet + "]"
Dim objCmdSelect As OleDbCommand = New OleDbCommand(expr, ExcelConnection)
Dim objDR As OleDbDataReader
Dim SQLconn As New SqlConnection()
Dim ConnString As String = "SERVER=SqlDEV;DATABASE=Freight;Integrated Security=True"
SQLconn.ConnectionString = ConnString
SQLconn.Open()
Using bulkCopy As SqlBulkCopy = New SqlBulkCopy(SQLconn)
bulkCopy.DestinationTableName = "dbo.test"
Try
objDR = objCmdSelect.ExecuteReader
Dim dt = New DataTable()
dt.Load(objDR)
DataGridView1.AutoGenerateColumns = True
DataGridView1.DataSource = dt
DataGridView1.Refresh()
bulkCopy.WriteToServer(objDR)
objDR.Close()
SQLconn.Close()
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Using
End Sub
Your reader object is being used by the DataTable, so comment out those lines and run them separately later with a new instance:
objDR = objCmdSelect.ExecuteReader
'Dim dt = New DataTable()
'dt.Load(objDR)
'DataGridView1.AutoGenerateColumns = True
'DataGridView1.DataSource = dt
'DataGridView1.Refresh()
bulkCopy.WriteToServer(objDR)

odbc reader for csv in vb.net

I'm writing a program that should handle million of datasets in csv in a short time, my idea was to use odbc because of performance reasons, therefore i read all the data with odbc and save it in memory, thereafter i add parameters and insert it in sql db, here is my code so far:
Using connection As New OdbcConnection("jdbc:odbc:Driver={Microsoft Text Driver (*.txt; *.csv)};" & filePath & "Extensions=csv;Persist Security Info=False;")
Dim reader As OdbcDataReader
Dim i As Integer
Dim r As SeekZeilen
Dim TextFileTable As DataTable = Nothing
Dim line As String = reader.Read()
Me.ParseString(line)
Dim memStream As New MemoryStream(Encoding.Default.GetBytes(line))
Using TextFileReader As New Microsoft.VisualBasic.FileIO.TextFieldParser(memStream)
TextFileReader.TextFieldType = FileIO.FieldType.Delimited
TextFileReader.SetDelimiters(";")
r.erste_Zeile = TextFileReader.ReadFields()
If TextFileTable Is Nothing Then
TextFileTable = New DataTable("TextFileTable")
For i = 0 To r.erste_Zeile.Length - 1
Dim Column As New DataColumn(r.erste_Zeile(i))
Column.ReadOnly = True
TextFileTable.Columns.Add(Column)
Next
End If
DataGridView1.DataSource = TextFileTable
End Using
While reader.HasRows
line = reader.Read()
Me.ParseString(line)
memStream = New MemoryStream(Encoding.Default.GetBytes(line))
Using TextFileReader As New Microsoft.VisualBasic.FileIO.TextFieldParser(memStream)
TextFileReader.TextFieldType = FileIO.FieldType.Delimited
TextFileReader.SetDelimiters(";")
DataGridView1.DataSource = TextFileTable
Try
r._Rest = TextFileReader.ReadFields()
ReplaceChars(r._Rest)
If Not r._Rest Is Nothing Then
Dim oSQL As New DBUmgebung.cdb.SQL()
oSQL.init()
AddParameters(oSQL, r)
oSQL.ausfuehrenSQL(DBUmgebung.cdb.KSQLCommand.INSERT, _table, "")
Dim dtRow As DataRow = TextFileTable.NewRow
For i = 0 To r._Rest.Length - 1
dtRow(i) = r._Rest(i).ToString()
Next
TextFileTable.Rows.Add(dtRow)
DataGridView1.Refresh()
Application.DoEvents()
End If
Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
MsgBox("Error! " & ex.Message & _
"")
Catch sqlEx As SqlException
MessageBox.Show(sqlEx.Message)
rtbSql.Focus()
Exit For
Catch ex As Exception
MessageBox.Show(ex.Message)
rtbSql.Focus()
Exit For
End Try
End Using
End While
reader.Close()
End Using
the problem is that i get null pointer exception for a unknown reason, does anyone have idea what i did wrong? is it probably because my odbc reader is not properly initialized?
Try this. This will read the csv file as all text into a datatable. Once in the Datatable you could then insert the records into SQL. You can always adjust this to handle multiple csv files.
Friend Shared Function GetExcelFile(ByVal strFileName As String, ByVal strPath As String) As DataTable
Try
Dim dt As New DataTable
Dim ConStr As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & strPath & ";Extended Properties=""Text;HDR=Yes;FMT=Delimited\"""
Dim conn As New OleDb.OleDbConnection(ConStr)
Dim da As New OleDb.OleDbDataAdapter("Select * from " & strFileName, conn)
da.Fill(dt)
Return dt
Catch ex As Exception
Return Nothing
End Try
End Function

Load Report failed with crystal report

I got an error (load report failed) when trying to print crystal report in my vb.net application
but my problem is (this error hasn't occurred always) maybe after printing unknown number of reports, then once this error has occurred.
Here is my code:
Dim cmd As New OleDbCommand
Dim connp As New OleDbConnection
Dim da As New OleDbDataAdapter
Dim ds As New DataSet
Dim strsql As String
Dim strreprotname As String
Try
connp.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" & Application.StartupPath & "\report.mdb; Jet OLEDB:Database Password=KNOZ1003"
connp.Open()
ds.Reset()
strsql = "select * from tab3"
cmd.CommandText = strsql
cmd.Connection = connp
da.SelectCommand = cmd
da.Fill(ds)
strreprotname = "cashrpt"
Dim strreportpath As String = Application.StartupPath & "\Reports\" & strreprotname & ".rpt"
Dim rptdocument As New CrystalDecisions.CrystalReports.Engine.ReportDocument
Dim prnset As New Printing.PrinterSettings
Dim pg As New Printing.PageSettings
rptdocument.Load(strreportpath)
rptdocument.SetDataSource(ds.Tables(0))
rptdocument.SetDatabaseLogon("", "", "", Application.StartupPath + "\report.mdb")
prnset.PrinterName = cashprinter
rptdocument.PrintToPrinter(prnset, pg, False)
cmd.Dispose()
connp.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try

cant find Isam installable CSV Files

Hey I am having a problem taking an excel spread sheet and inserting it into a data-grid in Visual Studio 2013 I was wondering if anyone could give me a hand.
Here is the code I have at the moment.
getting the error Could not find installable ISAM only when I have clicked on the csv fle iut works for ll the other files?
OpenFileDialog1.ShowDialog()
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
Case ".csv"
'CSV
conStr = String.Format(ExcelCsv, 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

Error "Child list for field [Sheet1$] cannot be created" when loading data from excel to datagridview

I am trying to fill the DataGridView (grvExcelData in this case) with data from an excel file. But I am getting the following error:
"Child list for field [Sheet1$] cannot be created"
Below is my code fragment where I am trying to fill the data grid view. Also I am using Visual Studio 2010 for programming
Thanks for your help in advance
Public Sub fillgrid()
Dim conn1 As String
conn1 = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & filenamepath & ";Extended Properties=""Excel 12.0;HDR=Yes;IMEX=2"""
Dim connection As OleDbConnection = New OleDbConnection(conn1)
Dim da As OleDbDataAdapter = New OleDbDataAdapter("SELECT * FROM [Sheet1$]", connection)
Dim ds As DataSet = New DataSet()
Dim emptyfile As String = "The file does not have any records for inserting."
Dim selectCmd As OleDbCommand = New OleDbCommand()
selectCmd.Connection = connection
selectCmd.CommandText = "SELECT * FROM [Sheet1$]"
If connection.State = ConnectionState.Closed Then
connection.Open()
End If
da.SelectCommand = selectCmd
Dim dsCounter As Integer = da.Fill(ds, "[Sheet1$]")
If dsCounter = 0 Then
MessageBox.Show(emptyfile, "dsCounter")
End If
grvExcelData.DataSource = ds
grvExcelData.DataMember = "Sheet1"
grvExcelData.SelectionMode = DataGridViewSelectionMode.FullRowSelect
da.Dispose()
If connection.State = ConnectionState.Open Then
connection.Close()
connection.Dispose()
End If
End Sub
Change
grvExcelData.DataMember = "Sheet1"
to
grvExcelData.DataMember = "[Sheet1$]"