I have scoured the net, and found many people asking this, yet none have fixed my answer.
I have a Connection Class, and a Method that uses that Class in a page.
DataConn.cs
public static OleDbConnection ConnectExcel()
{
//Store the connection details as a string
string connstr =
String.Format(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=pricelist.xlsx;Extended Properties=Excel 12.0 Xml;HDR=YES");
//Initialise the connection to the server using the connection string.
OleDbConnection oledbConn = new OleDbConnection(connstr);
//Open the connection, we do this here so we can instantly be able to use SQL commands in the code.
oledbConn.Open();
return oledbConn;
}
public static void DisconnectExcel()
{
_oledbConn.Dispose();
_oledbConn.Close();
}
And the code that calls it
protected void Page_Load(object sender, EventArgs e)
{
// Connection String
const string xlStr = "SELECT * FROM [Sheet2$]";
// Create OleDbCommand object and select data from worksheet Food
OleDbCommand cmd = new OleDbCommand(xlStr, DataConn.ConnectExcel());
// Create new OleDbDataAdapter
OleDbDataAdapter oleda = new OleDbDataAdapter();
oleda.SelectCommand = cmd;
// Create a DataSet which will hold the data extracted from the worksheet.
DataSet ds = new DataSet();
// Fill the DataSet from the data extracted from the worksheet.
oleda.Fill(ds);
// Bind the data to the GridView
gridPricelist.DataSource = ds;
gridPricelist.DataBind();
}
Yes I STILL get:
System.Data.OleDb.OleDbException: Could not find installable ISAM.
Can anyone please help?
If you use more than 1 extended property then the value tokens must be quoted, otherwise there is no way for the driver to distinguish them from the other non-extended properties in the connection string;
...Extended Properties=""Excel 8.0;IMEX=1"""
modify your connection string
String.Format(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=pricelist.xlsx;Extended Properties=""Excel 12.0 Xml;HDR=YES""");
reference:
Could not find installable ISAM
please "Extended Properties" put it in ' '.
That is, like the following statement:
string connStr =
String.Format(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=pricelist.xlsx;Extended Properties='Excel 12.0
Xml;HDR=YES'")
If you had installed LibreOffice look for cli_basetypes.dll, cli_cppuhelper.dll, cli_oootypes.dll, cli_uno.dll, cli_ure.dll, cli_uretypes.dll then add references to your project (to work with LibreOffice API's), I also installed "Microsoft Office Compatibility Pack for Word, Excel, and PowerPoint File Formats" and "Microsoft Access Database Engine 2010 Redistributable" (to get ACE.OLEDB.12.O connection without complete Office installation). This is a part of VB Sample in which I got the connection to oledb to create some queries.
OpenFileDialog.Filter = "Spreadsheets (*.xls*)|*.xls*"
OpenFileDialog.Multiselect = False
Try
If (OpenFileDialog.ShowDialog() = System.Windows.Forms.DialogResult.OK) Then
objOffice = CreateObject("com.sun.star.ServiceManager") 'preparar instancia libreOffice (prepare libreOffice instance)
instOffice = objOffice.createInstance("com.sun.star.frame.Desktop")
Dim obj(-1) As Object
Dim myDoc = instOffice.loadComponentFromURL("file:///" & OpenFileDialog.FileName.Replace("\", "/"), "_default", 0, obj)
Dim hojas = myDoc.getSheets().getElementNames() 'Obtener nombres de las hojas de calculo (get Spreadsheet names)
System.Threading.Thread.Sleep(1000) 'Esperar a que termine la instancia Office (await libreOffice thread)
myDoc.Close(True)
Dim MyConnection As System.Data.OleDb.OleDbConnection 'Preparar conexión para realizar consulta tipo sql (preparing connection)
Dim DtSet As System.Data.DataSet
Dim MyCommand As System.Data.OleDb.OleDbDataAdapter
If OpenFileDialog.FileName.ToUpper.Contains(".XLSX") Then
MyConnection = New System.Data.OleDb.OleDbConnection("provider=Microsoft.ACE.OLEDB.12.0;Data Source='" & OpenFileDialog.FileName & "';Extended Properties='Excel 12.0 Xml;HDR=YES;IMEX=1;'")
Else
MyConnection = New System.Data.OleDb.OleDbConnection("provider=Microsoft.ACE.OLEDB.12.0;Data Source='" & OpenFileDialog.FileName & "';Extended Properties='Excel 12.0;HDR=YES;IMEX=1'")
End If
Related
I'm working on a online test application in asp.net and i'm finding trouble in saving the checked answer status back to database, i.e once i click on next button in my aspx page these 2 things should happen
1)It should capture the currently checked option and add the value for that particular option as true into my database IS_Marked column.
2)It also should pull out the next set of question and Options
The latter is fine but i'm not getting any clue about how to save the checkd answer back into database
My aspx has 4 check boxes
and my next button click event is as follows,
protected void BtnNext_Click(object sender, EventArgs e)
{
if (qid == maxid)//checks whether current que id is equal to last que id in DB
{
BtnNext.Enabled = false; //if its last que then next button is disabled
}
else
{
BtnPrevious.Enabled = true; // if not last question next button is enabled
QuestionSet q = new QuestionSet(); //Question set is an entity to hold que text and options list
StudentB b = new StudentB(); //object of my business class
q = b.GetQuestion(1, 1, qid, 'N', 0);//passing student id, test id, question id, action taken, i.e button clicked(prev, next, last, first) and selected question(i.e any question that is present)
qid = Convert.ToInt32(q.Question_Id);
LblQStn.Text = q.Question_Text;
CheckBox1.Text = q.Options[0].Option_Text;//talking to business and model layer and getting que and ans from database and giving to checkboxes
CheckBox2.Text = q.Options[1].Option_Text;
CheckBox3.Text = q.Options[2].Option_Text;
CheckBox4.Text = q.Options[3].Option_Text;
}
}
now when he checks any answer i need to save its status as marked into the database
Any solution is highly appreciated,
thanks in advance
Well first you need to set up the connection to database. example:
//sqlString is your connectionstring//
dbconn = New SqlConnection(System.Configuration.ConfigurationManager.AppSettings("sqlString"))
dbconn.Open()
strsql = "INSERT INTO IS_Marked ([Mark]) VALUES ('" + Bedrijf + "')"
dbcomm = New SqlCommand(strsql, dbconn)
dbcomm.ExecuteNonQuery()
dbconn.Close()
This will be your basic sql command.
As you can see I ues ([yourvalue]) that what we are going to do next.
Dim dbconn As SqlConnection
Dim dbcomm As SqlCommand
Dim strsql, Checked_Mark As String
Mark = YourCheckBox.CheckedValue
So your final result will be like this:
Dim dbconn As SqlConnection
Dim dbcomm As SqlCommand
Dim strsql, Mark As String
Mark = YourCheckBox.CheckedValue
dbconn = New SqlConnection(System.Configuration.ConfigurationManager.AppSettings("sqlString"))
dbconn.Open()
strsql = "INSERT INTO IS_Marked ([Mark]) VALUES ('" + Bedrijf + "')"
dbcomm = New SqlCommand(strsql, dbconn)
dbcomm.ExecuteNonQuery()
dbconn.Close()
Im currently building a project that lets users import Excel files via a web interface (built), which saves the file to the server (built), and then imports the data into the SQL Database on the server depending on a few of the user options (not built).
Im not familiar with SQL database tools within VS at all so I have been fumbling around for the better part of two days just trying to get everything set up. Im pretty sure I need to use BulkCopy, but Im not quite sure how to use it and I can't seem to find specific examples that explain it pertaining to my specific application.
So in my App_Data folder I have an .mdf title "Device Database." In that database I have three tables: "Galaxy Nexus", "Hercules" , and "Ruby"
I am trying to import four cells from each imported excel sheet to their respective tables.
I would like to import cell(2,2) to column1 in the table, cell(2,3) to column2, cell(3,2) to column3 and cell(1,1) to column4.
The code I am trying to accomplish this with is:
Dim ExcelContentType As String = "application/vnd.ms-excel"
Dim Excel2010ContentType As String = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
Dim excelConnectionString As String = String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=Excel 8.0", SavedFile)
Using connection As New OleDbConnection(excelConnectionString)
Dim Command As OleDbCommand = New OleDbCommand("Select * FROM [Sheet1$]", connection)
connection.Open()
Using reader As DbDataReader = Command.ExecuteReader()
Dim sqlConnectionString As String = "Data Source=.\sqlexpress;Initial Catalog=ExcelDB;Integrated Security=True"
Using bulkCopy As New SqlBulkCopy(sqlConnectionString)
bulkCopy.DestinationTableName = DropDown1.SelectedItem.ToString
bulkCopy.WriteToServer(reader)
End Using
End Using
End Using
Where I am having trouble is, I do not know how to select certain cells from the excel sheet to import and I do not know how to copy those cells to specific columns in the specified table.
Any and all help is always appreciated.
Thanks,
Zach
Im posting an answer so that if anyone else stumbles upon this, they might be helped as well.
This is what got everything to work for me. (Shout out to kevin)
Protected Sub Button1_Click(sender As Object, e As System.EventArgs)
Dim appPath As String = Request.PhysicalApplicationPath
Dim con As New System.Data.SqlClient.SqlConnection
con.ConnectionString = "Data Source=.\SQLEXPRESS;AttachDbFilename=" & appPath & "App_Data\Devicedatabase.MDF;Integrated Security=True;User Instance=True;"
con.Open()
MsgBox("open")
con.Close()
MsgBox("close")
End Sub
This got the connection open after much trying and frustration.
This got the excel values imported to the database:
Using con As New SqlClient.SqlConnection With
{
.ConnectionString =
"Data Source=.\SQLEXPRESS;AttachDbFilename=" & appPath & "App_Data\Devicedatabase.MDF;Integrated Security=True;User Instance=True;"
}
Using cmd As New SqlClient.SqlCommand With
{
.Connection = con,
.CommandText = "INSERT INTO " & """" & DropDownList1.SelectedItem.ToString & """" & "ColumnName1, ColumnName2)VALUES (#Col1,#Col2)"
}
cmd.Parameters.Add(New SqlClient.SqlParameter With {.DbType = DbType.String, .ParameterName = "#Col1"})
cmd.Parameters.Add(New SqlClient.SqlParameter With {.DbType = DbType.String, .ParameterName = "#Col2"})
cmd.Parameters(0).Value = "Value obtained from Excel"
cmd.Parameters(1).Value = "Value obtained from Excel"
con.Open()
Dim Result As Integer = cmd.ExecuteNonQuery
If Result <> 1 Then
MessageBox.Show("Insert failed.")
Else
MessageBox.Show("Row inserted.")
End If
End Using
End Using
Enjoy guys!
Use Excel Data Reader dll for this. It will read the excel file and give the Dataset as result.
simple code for 'abcConnectionString' as a connection string
and 'pqr_table' as sql table.
'Sheet1' is for the sheet1 of excel file.
important thing is the table format ie rows n columns of excel n database file should b same
her is the vb.net code foe veb application
one FileUpload with name 'FileUpload1'
and one button.
this code is in side the buton method
Dim excelConnectionString As String = String.Empty
Dim uploadPath As String = "~/Uploads/"
Dim filePath As String = Server.MapPath(uploadPath + FileUpload1.PostedFile.FileName)
Dim fileExt As String = Path.GetExtension(FileUpload1.PostedFile.FileName)
Dim strConnection As [String] = ConfigurationManager.ConnectionStrings("abcConnectionString").ConnectionString
If fileExt = ".xls" OrElse fileExt = "XLS" Then
excelConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source='" & filePath & "'" & "; Extended Properties ='Excel 8.0;HDR=Yes'"
ElseIf fileExt = ".xlsx" OrElse fileExt = "XLSX" Then
excelConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & filePath & ";Extended Properties=Excel 12.0;Persist Security Info=False"
End If
Dim excelConnection As New OleDbConnection(excelConnectionString)
Dim cmd As New OleDbCommand("Select * from [Sheet1$]", excelConnection)
excelConnection.Open()
Dim dReader As OleDbDataReader
dReader = cmd.ExecuteReader()
Dim sqlBulk As New SqlBulkCopy(strConnection)
sqlBulk.DestinationTableName = "pqr_table"
sqlBulk.WriteToServer(dReader)
MsgBox("Congratulations! Successfully Imported.")
excelConnection.Close()
simple code for 'abcConnectionString' as a connection string and 'pqr_table' as sql table. 'Sheet1' is for the sheet1 of excel file. important thing is the table format ie rows n columns of excel n database file should b same
here is the vb.net code foe veb application one FileUpload with name 'FileUpload1' and one button. this code is in side the buton method
Dim excelConnectionString As String = String.Empty
Dim uploadPath As String = "~/Uploads/"
Dim filePath As String = Server.MapPath(uploadPath + FileUpload1.PostedFile.FileName)
Dim fileExt As String = Path.GetExtension(FileUpload1.PostedFile.FileName)
Dim strConnection As [String] = ConfigurationManager.ConnectionStrings("abcConnectionString").ConnectionString
If fileExt = ".xls" OrElse fileExt = "XLS" Then
excelConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source='" & filePath & "'" & "; Extended Properties ='Excel 8.0;HDR=Yes'"
ElseIf fileExt = ".xlsx" OrElse fileExt = "XLSX" Then
excelConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & filePath & ";Extended Properties=Excel 12.0;Persist Security Info=False"
End If
Dim excelConnection As New OleDbConnection(excelConnectionString)
Dim cmd As New OleDbCommand("Select * from [Sheet1$]", excelConnection)
excelConnection.Open()
Dim dReader As OleDbDataReader
dReader = cmd.ExecuteReader()
Dim sqlBulk As New SqlBulkCopy(strConnection)
sqlBulk.DestinationTableName = "pqr_table"
sqlBulk.WriteToServer(dReader)
MsgBox("Congratulations! Successfully Imported.")
excelConnection.Close()
I'm attempting to read a spreadsheet file called Book1.xls which contains a worksheet called Sheet1
However I'm getting the following error:
The Microsoft Jet database engine could not find the object 'Sheet1$'.
Make sure the object exists and that you spell its name and the path
name correctly.
Here is a snippet of the code I'm using:
Dim dt As DataTable = New DataTable()
Select Case fileExt
Case ".csv"
Dim reader As New CsvReader
dt = reader.GetDataTable(filePath)
Case ".xls", ".xlsx"
Dim oleDbConnStr As String
Select Case fileExt
Case ".xls"
oleDbConnStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & filePath & ";Extended Properties=""Excel 8.0;HDR=Yes;IMEX=2"""
Case ".xlsx"
oleDbConnStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & filePath & ";Extended Properties=""Excel 12.0;HDR=Yes;IMEX=2"""
End Select
Using oleDbConn As OleDbConnection = New OleDbConnection(oleDbConnStr)
oleDbConn.Open()
Dim oleDbCmd As New OleDbCommand("SELECT * FROM [Sheet1$]", oleDbConn)
Dim oleDbDa As New OleDbDataAdapter(oleDbCmd)
oleDbDa.Fill(dt)
oleDbConn.Close()
End Using
End Select
I can't understand why the code cannot find my worksheet. Why is this, and how can I resolve it?
I've found the problem.
It seems the spreadsheet was being saved to the wrong location, so filepath wasn't pointed to a file which exists.
I didn't check this at first because I assumed a different error message would appear. Something like "Book1.xls could not be found". However it seems like if it doesn't exist, then the message will just state that it cannot find the Worksheet.
If file name has additional dot character like below:
sample.data.csv
next select statement:
SELECT * FROM [sample.data.csv]
with connection string:
Provider=Microsoft.Jet.OLEDB.4.0;Data Source="C:\Data\"; Extended Properties="text;HDR=Yes;Format=Delimited;";
will fail with exception:
Additional information: The Microsoft Jet database engine could not find the object 'sample.data.csv'. Make sure the object exists and that you spell its name and the path name correctly.
Also - make sure you don't have the file open in Excel already. You won't be able to read the file if it's open somewhere else. I had the same error and realized I had the file open in Excel.
Not sure, I have some similar code (C#) that works well...
Maybe you can spot a difference?
string connectionString = string.Format(Thread.CurrentThread.CurrentCulture, "Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 12.0;HDR=YES;'", excelFilePath);
DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.OleDb");
using (DbConnection connection = factory.CreateConnection())
{
connection.ConnectionString = connectionString;
using (DbCommand command = connection.CreateCommand())
{
command.CommandText = #"SELECT [File], [ItemName], [ItemDescription], [Photographer name], [Date], [Environment site] FROM [Metadata$]";
connection.Open();
using (DbDataReader dr = command.ExecuteReader())
{
if (dr.HasRows)
{
while (dr.Read())
{
.......
}
}
}
connection.Close();
}
}
Try renaming your sheet; or explicitly adding columns; or checking if it's case sensitive.
Change your Excel file location, this error will be resolved.
may put your file in the same folder where your source present
best solution through vb coded from this link, all credits to these folks-
http://www.vbforums.com/showthread.php?507099-data-from-excel-sheet-to-datagrid-(vb)
C# My expected solution below
string connString = "Driver={Microsoft Excel Driver (*.xls)};READONLY=FALSE;DriverId=790;Dbq=" + "C:\\Users\\BHARAVI\\Documents\\visual studio 2013\\Projects\\ERP\\ERPAutomation\\Assets\\Data\\Data.xls";
OdbcConnection conn = new OdbcConnection(connString);
conn.ConnectionTimeout = 500;
OdbcCommand CMD = new OdbcCommand("SELECT * FROM [Sheet1$]", conn);
OdbcDataAdapter myDataAdaptor = new OdbcDataAdapter(CMD);
DataSet ds = new DataSet();
myDataAdaptor.Fill(ds ,"Sheet1");
DataTable dt = ds.Tables[0];
foreach (DataRow dr in dt.Rows)
{
loginId = dr["LoginId"].ToString();
encryptedPassword = dr["PWD"].ToString();
URL = dr["URL"].ToString();
}
Here's the code I'm using to show the Excel data on a Gridview:
if (FileUploadExcel.PostedFile.FileName.Contains(".xls"))
{
FileUploadExcel.SaveAs(Server.MapPath("~/Upload/") + "data.xls");
string connectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath("~/Upload/") + "data.xls;Extended Properties=Excel 8.0;";
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
connection.Open();
OleDbCommand command = new OleDbCommand("Select ID FROM [Sheet1$]", connection);
DataTable raw = new DataTable();
using (System.Data.Common.DbDataReader dr = command.ExecuteReader())
{
raw.Load(dr);
}
gv.DataSource = raw;
gv.DataBind();
}
}
This is what happens... I have this in my data.xls file:
ID
A-001
3929
B-001
When I upload that, the Gridview displays only these:
ID
A-001
B-001
Is there anything wrong with the code? Thanks.
Try to add IMEX=1 to your connection string.
It tells the driver to always read "intermixed" (numbers, dates, strings etc) data columns as text. Note that this option might affect excel sheet write access negative.
http://www.connectionstrings.com/excel
i need the complete code for retreiving the data from a database.. i m coding in visual web developer and using VB as coding language. I m using SQL SERVER as database handler.
Shared Dim con As SqlConnection
Shared Sub Main()
con = New SqlConnection("Server=(local)\SQLEXPRESS;Initial Catalog=MyDatabase;Integrated Security=SSPI")
' Create the command object
Dim str As String = "SELECT ID, FirstName, LastName FROM Employee"
Dim cmd As New SqlCommand(str, con)
Dim da As New SqlDataAdapter(cmd)
Dim ds As New DataSet()
da.Fill(ds, "Employee")
gridview1.datasource=ds;//
gridview1.databind();// to bind the data to gridview
its will be help to u..
Samples here might work for you