failed to read the excel to sql database - vb.net

I want to upload an Excel file and write data to sql server 2008.
The Excel file has 7 sheets and it writes in 7 tables.
Example : (sheetn -> temp_sheetn)
The code is working well but the last sheet is not writing in the last table.
The code is like this:
Partial Class app_UploadData
Inherits System.Web.UI.Page
Dim apps As New MyApps
Dim GlobReg As Integer = 0
Dim GlobOTC As Integer = 0
Private dt As DataTable = Nothing
Public Function xlsInsert(ByVal pth As String) As System.Data.DataTable
Dim strcon As String = String.Empty
If Path.GetExtension(pth).ToLower().Equals(".xls") OrElse Path.GetExtension(pth).ToLower().Equals(".xlsx") Then
strcon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & pth & ";Extended Properties=""Excel 8.0;HDR=YES;"""
Else
strcon = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & pth & ";Extended Properties=""Excel 12.0;HDR=YES;"""
End If
Dim strselect As String = "Select * from [Sheet1$]"
Dim exDT As New DataTable()
Using excelCon As New OleDbConnection(strcon)
Try
excelCon.Open()
Using exDA As New OleDbDataAdapter(strselect, excelCon)
exDA.Fill(exDT)
End Using
Catch oledb As OleDbException
Throw New Exception(oledb.Message.ToString())
Finally
excelCon.Close()
End Try
For i As Integer = 0 To exDT.Rows.Count - 1
' Check if first column is empty
' If empty then delete such record
If exDT.Rows(i)("CardNo").ToString() = String.Empty Then
exDT.Rows(i).Delete()
End If
Next
exDT.AcceptChanges()
' refresh rows changes
If exDT.Rows.Count = 0 Then
Throw New Exception("File uploaded has no record found.")
End If
Return exDT
End Using
End Function
Protected Sub btnUpload_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim ds As New DataSet()
Dim XlsConnString As String = String.Empty
Dim DirPath As String = Server.MapPath("~/Temp_Upload/")
Dim fName As String
If (Directory.Exists(DirPath)) Then
For Each fName In Directory.GetFiles(DirPath)
If File.Exists(fName) Then
File.Delete(fName)
End If
Next
End If
If xlsUpload.HasFile Then
Dim fileName As String = Path.GetFileName(xlsUpload.PostedFile.FileName)
Dim fileExtension As String = Path.GetExtension(xlsUpload.PostedFile.FileName)
Dim fileLocation As String = Server.MapPath("~/Temp_Upload/" & fileName)
xlsUpload.SaveAs(fileLocation)
'Check whether file extension is xls or xslx
If fileExtension = ".xls" Then
XlsConnString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & fileLocation & ";Extended Properties=""Excel 8.0;HDR=Yes;IMEX=2"""
ElseIf fileExtension = ".xlsx" Then
XlsConnString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & fileLocation & ";Extended Properties=""Excel 12.0;HDR=Yes;IMEX=2"""
ElseIf fileExtension <> ".xls" Or fileExtension <> ".xlsx" Then
lblMessage.Text = "Upload file must be excel !"
Exit Sub
End If
Dim cmd As New SqlCommand : Dim SheetName As String 'Dim dr As SqlDataReader
'Dim tran As SqlTransaction
apps.OpenConnection()
cmd.Connection = apps.oConn
Dim cn As New OleDbConnection(XlsConnString)
Try
cn.Open()
Catch ex As OleDbException
Console.WriteLine(ex.Message)
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
' It Represents Excel data table Schema.
Dim dt As New System.Data.DataTable()
dt = cn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, Nothing)
If dt IsNot Nothing OrElse dt.Rows.Count > 0 Then
For sheet_count As Integer = 1 To dt.Rows.Count - 1
Try
' Create Query to get Data from sheet.
SheetName = dt.Rows(sheet_count)("table_name").ToString()
'Dim da As New OleDbDataAdapter("SELECT * FROM [" & sheetname & "]", cn)
'da.Fill(ds, sheetname)
'Execute a query to erase any previous data from our destination table
cmd.CommandText = "Truncate Table Temp_" & SheetName
cmd.ExecuteNonQuery()
'Series of commands to bulk copy data from the excel file into our SQL table
Dim OleDbConn As OleDbConnection = New OleDbConnection(XlsConnString)
Dim OleDbCmd As OleDbCommand = New OleDbCommand(("SELECT * FROM [" & SheetName & "]"), OleDbConn)
'Dim OleDbCmd As OleDbCommand = New OleDbCommand(("SELECT * FROM [Customer$]"), OleDbConn)
OleDbConn.Open()
Dim OleDbRead As OleDbDataReader = OleDbCmd.ExecuteReader()
Dim bulkCopy As SqlBulkCopy = New SqlBulkCopy(apps.oConn)
bulkCopy.DestinationTableName = "Temp_" & SheetName
bulkCopy.WriteToServer(OleDbRead)
OleDbConn.Close()
OleDbConn = Nothing
Catch ex As DataException
Console.WriteLine(ex.Message)
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
Next
End If
cn.Close()
cn = Nothing
apps.CloseConnection()
End If
End Sub
End Class

The line that reads
For sheet_count As Integer = 1 To dt.Rows.Count - 1
should either be
For sheet_count As Integer = 0 To dt.Rows.Count - 1
or
For sheet_count As Integer = 1 To dt.Rows.Count
The first one I suspect, but I can't remember if this is a zero based list as I haven't got VB.Net installed here.
Incidentally there's no need to check the file extension is .xls and then to use the Jet provider, Microsoft.ACE.OLEDB.12.0 will work just fine on .xls files.

Related

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

Having trouble with OleDbConnection

I'm working on a program that will go out to an access database, wipe out the records for all 4 of the tables that I specify, before creating a new table in the database that contains all of the data from my Excel "Table of Contents" file. I'm having trouble with the OleDbConnection side of things. It keeps erroring out on the line that contains conn.Open() with the error "Invalid Argument"
My code is as follows:
Private Sub btnAccess_Click(sender As System.Object, e As System.EventArgs) Handles btnAccess.Click
Dim AccessPath As String = ""
Dim com1 As OleDbCommand
Dim com2 As OleDbCommand
Dim com3 As OleDbCommand
Dim com4 As OleDbCommand
Dim DatabaseFile As String = ""
Dim DatabaseFileTitle As String = ""
Dim ExcelFile As String = ""
Dim ExcelFileTitle As String = ""
Dim connect As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & ExcelFile & _
";Extended Properties=Excel 12.0;"
OpenFileDialog2.DefaultExt = "*.accdb"
MsgBox("Select the ACCESS FILE from the working directory.", , "BROWSE FOR THE ACCESS DATABASE")
OpenFileDialog2.InitialDirectory = Microsoft.VisualBasic.FileIO.FileSystem.CurrentDirectory
'Text (*.txt)|*.txt|Pictures (*.bmp;*.ico)|*.bmp;*.ico
OpenFileDialog2.Filter = "Access Database (*.accdb)|*.accdb"
OpenFileDialog2.Title = "Select ACCESS DATABASE File."
OpenFileDialog2.ShowDialog()
DatabaseFile = OpenFileDialog2.FileName
DatabaseFileTitle = System.IO.Path.GetFileNameWithoutExtension(OpenFileDialog2.FileName)
OpenFileDialog3.DefaultExt = "*.xlsx"
MsgBox("Select the EXCEL TOC FILE from the working directory.", , "BROWSE FOR THE EXCEL TOC")
OpenFileDialog3.InitialDirectory = Microsoft.VisualBasic.FileIO.FileSystem.CurrentDirectory
'Text (*.txt)|*.txt|Pictures (*.bmp;*.ico)|*.bmp;*.ico
OpenFileDialog3.Filter = "Excel Spreadhseet (*.xlsx)|*.xlsx"
OpenFileDialog3.Title = "Select EXCEL TOC File."
OpenFileDialog3.ShowDialog()
ExcelFile = OpenFileDialog3.FileName
ExcelFileTitle = System.IO.Path.GetFileNameWithoutExtension(OpenFileDialog3.FileName)
Using conn As New OleDbConnection(connect)
Using cmd As New OleDbCommand()
cmd.Connection = conn
cmd.CommandText = "SELECT * INTO [MS Access;Database=" & DatabaseFile & "].[New Table] FROM [Sheet1$]"
conn.Open()
cmd.ExecuteNonQuery()
com1 = New OleDbCommand("delete from tblArtId", conn)
com2 = New OleDbCommand("delete from tblFigure", conn)
com3 = New OleDbCommand("delete from tblSubGroups", conn)
com4 = New OleDbCommand("delete from tblGroups", conn)
com1.ExecuteNonQuery()
com2.ExecuteNonQuery()
com3.ExecuteNonQuery()
com4.ExecuteNonQuery()
conn.Close()
End Using
End Using
MsgBox("Records Deleted")
End Sub
If anyone is curious....my updated code is as follows:
Private Sub btnAccess_Click(sender As System.Object, e As System.EventArgs) Handles btnAccess.Click
Dim AccessPath As String = ""
Dim com1 As OleDbCommand
Dim com2 As OleDbCommand
Dim com3 As OleDbCommand
Dim com4 As OleDbCommand
Dim DatabaseFile As String = ""
Dim DatabaseFileTitle As String = ""
Dim ExcelFile As String = ""
Dim ExcelFileTitle As String = ""
OpenFileDialog2.DefaultExt = "*.accdb"
MsgBox("Select the ACCESS FILE from the working directory.", , "BROWSE FOR THE ACCESS DATABASE")
OpenFileDialog2.InitialDirectory = Microsoft.VisualBasic.FileIO.FileSystem.CurrentDirectory
'Text (*.txt)|*.txt|Pictures (*.bmp;*.ico)|*.bmp;*.ico
OpenFileDialog2.Filter = "Access Database (*.accdb)|*.accdb"
OpenFileDialog2.Title = "Select ACCESS DATABASE File."
OpenFileDialog2.ShowDialog()
DatabaseFile = OpenFileDialog2.FileName
DatabaseFileTitle = System.IO.Path.GetFileNameWithoutExtension(OpenFileDialog2.FileName)
OpenFileDialog3.DefaultExt = "*.xlsx"
MsgBox("Select the EXCEL TOC FILE from the working directory.", , "BROWSE FOR THE EXCEL TOC")
OpenFileDialog3.InitialDirectory = Microsoft.VisualBasic.FileIO.FileSystem.CurrentDirectory
'Text (*.txt)|*.txt|Pictures (*.bmp;*.ico)|*.bmp;*.ico
OpenFileDialog3.Filter = "Excel Spreadhseet (*.xlsx)|*.xlsx"
OpenFileDialog3.Title = "Select EXCEL TOC File."
OpenFileDialog3.ShowDialog()
ExcelFile = OpenFileDialog3.FileName
ExcelFileTitle = System.IO.Path.GetFileNameWithoutExtension(OpenFileDialog3.FileName)
Dim connectExcel As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & ExcelFile & _
";Extended Properties=Excel 12.0;"
Dim connectAccess As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & DatabaseFile & ";"
Using connExcel As New OleDbConnection(connectExcel)
Using cmd As New OleDbCommand()
cmd.Connection = connExcel
cmd.CommandText = "SELECT * INTO [MS Access;Database=" & DatabaseFile & "].[New Table] FROM [TOC Output for Excel$]"
connExcel.Open()
cmd.ExecuteNonQuery()
connExcel.Close()
End Using
End Using
Using connAccess As New OleDbConnection(connectAccess)
Using cmdAccess As New OleDbCommand()
com1 = New OleDbCommand("delete from tblArtId", connAccess)
com2 = New OleDbCommand("delete from tblFigure", connAccess)
com3 = New OleDbCommand("delete from tblSubGroups", connAccess)
com4 = New OleDbCommand("delete from tblGroups", connAccess)
connAccess.Open()
com1.ExecuteNonQuery()
com2.ExecuteNonQuery()
com3.ExecuteNonQuery()
com4.ExecuteNonQuery()
connAccess.Close()
End Using
End Using
MsgBox("Staging Table has been created. All Records Deleted from Group, SubGroup, Figure, and ArtID tables")
End Sub

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

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

Prevent Excel pop up message in VB code

I am having a problem with the "File Now Available" message box popping open from excel when i importing a file to my program.
http://oi50.tinypic.com/23wajt.jpg
Private Function XLSSelect_Click(strFileName As String) As DataTable
Dim connectionStringTemplate As String = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source={0};" + "Extended Properties=""Excel 12.0;HDR=Yes;IMEX=1"""
Dim connectionString As String = String.Format(connectionStringTemplate, strFileName)
Try
Dim sqlSelect As String = "SELECT * FROM [" & GetExcelSheetNames(strFileName)(0) & "];"
' Load the Excel worksheet into a DataTable
Dim workbook As DataSet = New DataSet()
Dim excelAdapter As System.Data.Common.DataAdapter = New System.Data.OleDb.OleDbDataAdapter(sqlSelect, connectionString)
excelAdapter.Fill(workbook)
For i As Integer = 0 To workbook.Tables(0).Columns.Count - 1
workbook.Tables(0).Columns(i).ColumnName = workbook.Tables(0).Columns(i).ColumnName.ToString.Trim.Replace(" ", "")
Next
Return workbook.Tables(0).Copy
Catch
Throw New Exception("Error reading from Excel Spreadsheet. Are you sure this file isn't currently open in Excel, and that it has been saved as a .xls through Excel at least once?")
End Try
Return Nothing
End Function
Private Shared Function GetExcelSheetNames(excelFile As String) As [String]()
Dim objConn As OleDbConnection = Nothing
Dim dt As System.Data.DataTable = Nothing
Try
Dim connString As [String] = "Provider=Microsoft.ACE.OLEDB.12.0;" & "Data Source=" & excelFile & ";Extended Properties=Excel 12.0;"
' Create connection object by using the preceding connection string.
objConn = New OleDbConnection(connString)
' Open connection with the database.
objConn.Open()
' Get the data table containg the schema guid.
dt = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, Nothing)
If dt Is Nothing Then
Return Nothing
End If
Dim excelSheets As [String]() = New [String](dt.Rows.Count - 1) {}
Dim i As Integer = 0
'Add the sheet name to the string array.
For Each row As DataRow In dt.Rows
excelSheets(i) = row("TABLE_NAME").ToString()
i += 1
Next
Return excelSheets
Catch ex As Exception
Return Nothing
Finally
' Clean up.
If objConn IsNot Nothing Then
objConn.Close()
objConn.Dispose()
End If
If dt IsNot Nothing Then
dt.Dispose()
End If
End Try
End Function
Anyone know how i can go about disabling this ?
Dim appExcel As Excel.Application
Set appExcel = New Excel.Application
appExcel.Workbooks.Open "e:\development\test.xls", 0
' Do your thing here...
appExcel.DisplayAlerts = False ' Surpress save dialog box.
appExcel.Quit ' Quit without saving. you can change as you want
Set appExcel = Nothing
in your code
Try
Dim connString As [String] = "Provider=Microsoft.ACE.OLEDB.12.0;" & "Data Source=" & excelFile & ";Extended Properties=Excel 12.0;"
' Create connection object by using the preceding connection string.
objConn = New OleDbConnection(connString)
' Open connection with the database.
objConn.Open()
appExcel.DisplayAlerts = False ' try here!
' Get the data table containg the schema guid.
dt = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, Nothing)
Sources : http://www.xtremevbtalk.com/showthread.php?t=16007