I'm trying to import an Excel file into a DataSet in VB. My code that I'm using for this looks like this:
Dim StrSql
Dim ExcelCon As New OleDbConnection
Dim ExcelAdp As OleDbDataAdapter
Dim ExcelComm As OleDbCommand
Dim Col1 As DataColumn
Try
ExcelCon.ConnectionString = "Provider=SQLNCLI11;" & _
"Data Source = " & strpath & _
";Extended Properties=""Excel 8.0;"""
ExcelCon.Open()
StrSql = "SELECT * From [$Sheet1$]"
ExcelComm = New OleDbCommand(StrSql, ExcelCon)
ExcelAdp = New OleDbDataAdapter(ExcelComm)
objDT = New DataTable()
ExcelAdp.Fill(objDT)
Col1 = New DataColumn
Col1.DefaultValue = 0
Col1.DataType = System.Type.GetType("System.Decimal")
Col1.Caption = "Sr No."
Col1.ColumnName = "SrNo"
objDT.Columns.Add(Col1)
Col1.SetOrdinal(1)
ExcelCon.Close()
Catch ex As Exception
Finally
ExcelCon = Nothing
ExcelAdp = Nothing
ExcelComm = Nothing
End Try`
The error I am receiving says "Invalid connection string attribute". Does anyone know how to fix this error? I am using Excel 2010, if that helps. Thanks in advance.
Related
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
I had my code working just fine, but when I generated new updated versions of the CSV files it suddenly errors out on me and gives me a type mismatch catch.
Here is the code that I have right now.
Dim A As String = "ADusers.csv"
Dim B As String = "MlnExp.csv"
Dim filePath As String = "C:\CSV"
Try
Dim ConnectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & (filePath) & "\;Extended Properties='text;HDR=Yes'"
Dim sSql As String = "SELECT *" _
& "FROM ([" & (B) & "] B LEFT JOIN [" & (A) & "] A ON B.EmployeeNumber = A.employeeID)"
Dim conn As OleDb.OleDbConnection = New OleDb.OleDbConnection(ConnectionString)
Dim Command As OleDb.OleDbCommand = New OleDb.OleDbCommand(sSql, conn)
Command.CommandType = CommandType.Text
conn.Open()
Dim da As OleDb.OleDbDataAdapter = New OleDb.OleDbDataAdapter(sSql, conn)
Dim dt As DataTable = New DataTable
da.Fill(dt)
DataGrid1.DataSource = dt
DataGrid1.Update()
conn.Close()
lblStatus.Text = "CSV combined... Now saving to file."
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Exclamation)
End Try
Before it would go through, combine the two CSV files, and then display them in my datagrid. But now my catch is throwing back
Type mismatch in expression
i would check B.EmployeeNumber = A.employeeID
in both of your file one is a text value (left align) and the other is a a interger(right align)
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$]"
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
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