Error when trying to read data from Excel in VB.Net - 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

Related

Create table from Excel file

I'm trying to create a temp table on my database from an Excel file uploaded by the user. I cannot understand where is the problem and why Visual Studio is throwing that exception.
Code
Private Sub Excel_Load(ByVal filePath As String)
Dim myConn As SqlConnection
Dim myCmd As SqlCommand
Dim sqlCmd As String
Dim filename As String = Path.GetFileNameWithoutExtension(filePath)
'Setting up Connection'
myConn = New SqlConnection("Server=*****;Database=*****;User ID=*****;Password=*****;Integrated Security=SSPI;")
myConn.Open()
'Create table'
sqlCmd = "CREATE TABLE XlsTemp AS (SELECT * FROM EXCELLINK [" & filename & "$])"
'Execute Query'
myCmd = myConn.CreateCommand()
myCmd.CommandText = sqlCmd
myCmd.ExecuteNonQuery()
myConn.Close()
End Sub
Exception
SqlException: The object name 'EXCELLINK' is not valid.
Peu_UNRAE is my Excel file.
At the end I come up with this solution:
Dim MyConnection As System.Data.OleDb.OleDbConnection
Dim fileExcelType As String
//Get the file extension in order to use the propper provider
If IO.Path.GetExtension(fileExcel.ToUpper) = ".XLS" Then
fileExcelType = "Excel 8.0"
MyConnection = New System.Data.OleDb.OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0;Data Source='" & fileExcel & "';Extended Properties=" & fileExcelType & ";")
Else
fileExcelType = "Excel 12.0"
MyConnection = New System.Data.OleDb.OleDbConnection("provider=Microsoft.ACE.OLEDB.12.0;Data Source='" & fileExcel & "';Extended Properties=" & fileExcelType & ";")
End If
//Opening excel connection
MyConnection.Open()
Dim myTableName = MyConnection.GetSchema("Tables").Rows(0)("TABLE_NAME")
Dim MyCommand As OleDbDataAdapter = New OleDbDataAdapter(String.Format("SELECT * FROM [{0}] ", myTableName), MyConnection)
MyCommand.TableMappings.Add("Table", " ")
MyCommand.Fill(dt)
//Closing connection
MyConnection.Close()
Remarks:
I used // for the comments because the standar ' was giving some problem here on StackOverflow

Set datasource of datagridview in module

I am writing a program that will automatically process files, based on a set of criteria. In order to process these, I need to load the Excel file first, before I can process it.
I create a module called "NewBusAuto". In here, I created a new datagridview. I am trying to set the datasource of this, but whenever I do, it doesn't actually bind. When I try and process each row/column, it is saying it is still empty.
Code used:
Module m_NewBusinessAutomation
Dim dgvImport As DataGridView
Public Sub NewBusAuto(ByVal folderName As String,
ByVal fileName As String,
ByVal executeScript As String)
dgvImport = New DataGridView
If Path.GetExtension(fileName) = ".xls" Or Path.GetExtension(fileName) = ".xlsx" Then
Using cn As New System.Data.OleDb.OleDbConnection
Dim builder As New OleDbConnectionStringBuilder With _
{.DataSource = folderName & "\" & fileName,
.Provider = "Microsoft.ACE.OLEDB.12.0"}
builder.Add("Extended Properties", "Excel 12.0; IMEX=1;HDR=Yes;")
cn.ConnectionString = builder.ConnectionString
cn.Open()
Using cmd As OleDbCommand = New OleDbCommand With {.Connection = cn}
cmd.CommandText = "SELECT * FROM [Sheet1$]"
Dim dr As System.Data.IDataReader = cmd.ExecuteReader
Dim dt As New DataTable
dt.Load(dr)
dgvImport.DataSource = dt
dgvImport.Refresh()
Messagebox.show(dgvImport.RowCount & "-" & dgvImport.ColumnCount)
dr.Close()
End Using
End Using
End If
The messagebox is giving me "0 - 0" as a result.
I need to load the Excel file to the actual database. Any help would be appreciated!

Uploading Excel File into MS Access using vb.net

I am trying to import an Excel file into an Access DB via vb.net
the idea is the customer can export the data into excel, modify it, add, delete them importing it back.
The data exported has exactly the same format than the table to import to.
I am using the code below:
Try
Dim strFileName As String = String.Empty
Dim XLda As New OleDbDataAdapter
Dim ExcelTables As New DataTable
Dim StrSelect = "SELECT * FROM [{0}]"
OpenFileDialog1.FileName = ""
OpenFileDialog1.InitialDirectory = mdlGlobalStuff.sMasterDataPath
OpenFileDialog1.Filter = "Excel|*.xls|All files (*.*)|*.*"
If OpenFileDialog1.ShowDialog() <> Windows.Forms.DialogResult.OK Then
Exit Sub
End If
strFileName = OpenFileDialog1.FileName
Dim MyXLConnection As New OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0; Data Source=" & strFileName & ";Extended Properties=Excel 8.0;")
Using MyXLConnection
Using cmd As New OleDbCommand
cmd.Connection = MyXLConnection
cmd.CommandText = "INSERT INTO [MS Access;Database=InvoicingToolDB.accdb].[tbl_Bases] SELECT * FROM [Sheet1$]"
If MyXLConnection.State = ConnectionState.Open Then
MyXLConnection.Close()
End If
MyXLConnection.Open()
cmd.ExecuteNonQuery()
End Using
End Using
Catch ex As Exception
MsgBox("ImportLinkLabel_LinkClicked: Importing Base data" & vbCrLf & ErrorToString())
End Try
I always have an error message saying:
Unrecognized database format 'c:\--path to db--\InvoicingToolDB.accdb'
The path is correct and I don't understand why the format wouldn't be recognized.
Ok I have found the issue. The OLEDB Provider version was not the right one (4.0 is not reading Access .accdb format but old .mdb format only)
Replacing:
Dim MyXLConnection As New OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0; Data Source=" & strFileName & ";Extended Properties=Excel 8.0;")
With:
Dim MyXLConnection As New leDbConnection("provider=Microsoft.ACE.OLEDB.12.0; Data Source=" & strFileName & ";Extended Properties=Excel 8.0;")
Works perfectly.

could not find installable isam [vb.net]

I have the following problem, by using the connection string:
"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filename +
";Extended Properties=Excel 12.0 Xml;"
Then, I can execute the open-task. Nevertheless, if I want to use the following connection string:
"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filename +
";Extended Properties=Excel 12.0 Xml;HDR=NO"
I get a mistake, saying me that the installable isam could not be found.
What is wrong with the second connection string, as I need this one because in my worksheet no headers are used.
Thanks in advance
if you want to query excel you must have a '$' sign after the sheet name in order to define the sheet as a table.
anyway that is the code i wrote for that purpose:
Try
Dim Myconnetion As New OleDbConnection
Dim DataSet As System.Data.DataSet
Dim MyCOmmand As System.Data.OleDb.OleDbDataAdapter
Dim Path As String = fullpath
Myconnetion = New System.Data.OleDb.OleDbConnection("provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Path + ";Extended Properties=Excel 12.0;")
MyCOmmand = New System.Data.OleDb.OleDbDataAdapter("SELECT * FROM " & "[" & sheetname & "$]")
DataSet = New System.Data.DataSet
MyCOmmand.Fill(DataSet)
dgv.DataSource = DataSet.Tables(0)
Myconnetion.Close()
Catch ex As Exception
MsgBox(ex.Message.ToString)
End Try

Closing an OLE DB connection opened from within a function

Backed myself in a corner....
Used a piece of code I found on the web and can't figure out how to close this connection. The returned OleDbcommand objCommand remains open after processing. I need to it close so I can delete the file after I have pulled the data from it. (Don't want them hanging around on the server.)
This has to be easier than the 100 of lines of code that I have tried to do this. This function opens the connection.
Protected Function ExcelConnection() As OleDbCommand
Dim fileName As String = Session("newUploadedFile")
' Connect to the Excel Spreadsheet
Dim xConnStr As String = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=" & Server.MapPath(String.Format("~/Upload/{0}", fileName)) & ";" & _
"Extended Properties=Excel 8.0;"
' create your excel connection object using the connection string
Dim objXConn As New OleDbConnection(xConnStr)
objXConn.Open()
' use a SQL Select command to retrieve the data from the Excel Spreadsheet
' the "table name" is the name of the worksheet within the spreadsheet
' in this case, the worksheet name is "Sheet1" and is expressed as: [Sheet1$]
Dim objCommand As New OleDbCommand("SELECT Name FROM [Sheet1$]", objXConn)
Return objCommand
End Function
I have tried...
ExcelConnection.connection.close()
along with about 40 other attempts to recreate the Command and then close it.
Could really use some help on this one.
This is probably not the best way to do this, but if you really must do it this way consider defining and opening the connection in the calling routine and passing it into this routine as a parameter. It can then be closed in the calling routing, thus...
Sub Main()
Dim xConnStr As String = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=" & Server.MapPath(String.Format("~/Upload/{0}", fileName)) & ";" & _
"Extended Properties=Excel 8.0;"
Dim objXConn As New OleDbConnection(xConnStr)
objXConn.Open()
Dim ObjCommand As New OleDbCommand = ExcelConnection(objXConn)
'Whatever other operations you want to do with your returned OleDbCommand
...
objXConn.Close()
End Sub
Function ExcelConnection(PassedConnection As OleDbConnection) As OleDbCommand
Dim fileName As String = Session("newUploadedFile")
Dim objCommand As New OleDbCommand("SELECT Name FROM [Sheet1$]", PassedConnection)
Return objCommand
End Function
I posted something similar to this here... Best fastest way to read an Excel sheet