am getting the following error while trying to import data from excel to the database.
The Microsoft Office Access database engine could not find the object
'C:\Users\DAKTARI\Desktop\smarttable.xls'
this is my code behind that am using.
public partial class Smarttable : System.Web.UI.Page
{
OleDbConnection Econ;
SqlConnection con;
string constr, Query, sqlconn;
protected void Page_Load(object sender, EventArgs e)
{
}
private void ExcelConn(string FilePath)
{
constr = string.Format(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\DAKTARI\Desktop\smarttable.xls;Extended Properties=""Excel 12.0 Xml;HDR=YES;""");
Econ = new OleDbConnection(constr);
}
private void connection()
{
sqlconn = ConfigurationManager.ConnectionStrings["SqlCom"].ConnectionString;
con = new SqlConnection(sqlconn);
}
private void InsertExcelRecords(string FilePath)
{
ExcelConn(FilePath);
Query = string.Format("Select [InvoiceNumber],[AmountPaid],[Remarks] FROM [C:\\Users\\DAKTARI\\Desktop\\smarttable.xls]", "Orders$");
OleDbCommand Ecom = new OleDbCommand(Query, Econ);
Econ.Open();
DataSet ds = new DataSet();
OleDbDataAdapter oda = new OleDbDataAdapter(Query, Econ);
Econ.Close();
oda.Fill(ds);
DataTable Exceldt = ds.Tables[0];
connection();
//creating object of SqlBulkCopy
SqlBulkCopy objbulk = new SqlBulkCopy(con);
//assigning Destination table name
objbulk.DestinationTableName = "smarttable";
//Mapping Table column
objbulk.ColumnMappings.Add("InvoiceNumber", "InvoiceNumber");
objbulk.ColumnMappings.Add("AmountPaid", "AmountPaid");
objbulk.ColumnMappings.Add("Remarks", "Remarks");
//inserting Datatable Records to DataBase
con.Open();
objbulk.WriteToServer(Exceldt);
con.Close();
}
protected void Button1_Click(object sender, EventArgs e)
{
string CurrentFilePath = Path.GetFullPath(FileUpload1.PostedFile.FileName);
InsertExcelRecords(CurrentFilePath);
}
}
Your Excel file format uses XLS which means for Office 2003 or earlier, but you're using ACE OLEDB provider which used for Office 2007 or later:
constr = string.Format(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\DAKTARI\Desktop\smarttable.xls;Extended Properties=""Excel 12.0 Xml;HDR=YES;"");
The correct usage is using Jet 4.0 provider like this:
constr = string.Format(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties='Excel 8.0;HDR=YES;'", FilePath);
Also you have second issue which a wrong query string is used to read the data inside worksheet:
Query = string.Format("Select [InvoiceNumber],[AmountPaid],[Remarks] FROM [C:\\Users\\DAKTARI\\Desktop\\smarttable.xls]", "Orders$");
This should be changed to proper form below:
Query = "SELECT [InvoiceNumber],[AmountPaid],[Remarks] FROM [Orders$]";
Change this line
Query = string.Format("Select [InvoiceNumber],[AmountPaid],[Remarks] FROM [C:\\Users\\DAKTARI\\Desktop\\smarttable.xls]", "Orders$");
To
Query = "Select [InvoiceNumber],[AmountPaid],[Remarks] FROM [Orders$]";
The FROM needs to be followed by the Sheet Name which is treated like a table
Related
this same code has worked for several other programs, however i can not get it to function with this program for some reason. what is happening is i select a file location on my desktop to read from, but the program keeps trying to open the file from inside the program files of where i have this program saved.
MessageBox.Show(PATHTEXTBOX.Text);
string connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath;
string query = "select * from Vendors";
OleDbConnection connect = new OleDbConnection(connString);
OleDbCommand command = new OleDbCommand(query, connect);
connect.Open();
OleDbDataReader reader = command.ExecuteReader();
DataTable dataTable = new DataTable();
dataTable.Load(reader);
dataGridView1.DataSource = dataTable.DefaultView;
connect.Close();
Querying the database using the "SqlDataAdapter" object was successful. I made a case to reproduce your problem and realized the query to the database.
UI page:
Vendors table data:
Test Results:
Code logic:
Query the database by clicking the test button.
Bind the DataGridView control by using code.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string connStr = #"Data Source=(localdb)\ProjectModels;Initial Catalog=Test;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False";
//Create an instance of SqlConnection
SqlConnection conn = null;
try
{
conn = new SqlConnection(connStr);
//open database
conn.Open();
string sql = "select * from Vendors";
//Create an object of the SqlDataAdapter class
SqlDataAdapter sda = new SqlDataAdapter(sql, conn);
//Create an object of the DataSet class
DataSet ds = new DataSet();
//Use the SqlDataAdapter object sda to fill the new lookup results into the DataSet object ds
sda.Fill(ds);
//Set the DataSource property of the table control
dataGridView1.DataSource = ds.Tables[0];
}
catch (Exception ex)
{
MessageBox.Show("An error occurred!" + ex.Message);
}
finally
{
if (conn != null)
{
//Close the database connection
conn.Close();
}
}
}
}
It may be helpful to check your database connection string. Hope that helps you.
First of all, here is my code:
private void Form5_Load(object sender, EventArgs e)
{
string strProvider = #"Provider = Microsoft.ACE.OLEDB.12.0; Data Source = c:\Users\name\Documents\myprogramms\example.accdb";
string strSql = "Select * from score";
OleDbConnection con = new OleDbConnection(strProvider);
OleDbCommand cmd = new OleDbCommand(strSql, con);
con.Open();
cmd.CommandType = CommandType.Text;
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataTable scores = new DataTable();
da.Fill(scores);
data_example.DataSource = scores;
}
My goal is to display the data out of a MS Access Database. My codes has no error messages, but everytime I try to open the Data Grid View its completely empty.
your code snippet looks good. I cannot see any obvious issue.
Try to put breakpoint at the end of your method and check if datatable contains rows and rows contains any values in ItemArray.
Make sure your data_example DataGridView control is set AutoGenerateColumns = true (default) and check you have no other data source defined for your data_example DataGridView control. This code works for me.
private void Form1_Load(object sender, EventArgs e)
{
data_example.AutoGenerateColumns = true;
string strProvider = #"Provider = Microsoft.ACE.OLEDB.12.0; Data Source = c:\aaa\CinemaBooking.accdb";
string strSql = "Select * from Booking";
using (OleDbConnection con = new OleDbConnection(strProvider))
{
using (OleDbCommand cmd = new OleDbCommand(strSql, con))
{
using (OleDbDataAdapter da = new OleDbDataAdapter(cmd))
{
con.Open();
var scores = new DataTable();
da.Fill(scores);
data_example.DataSource = scores.DefaultView;
con.Close();
}
}
}
}
Maybe you can try to fill dataset with adapter and then use named table as datasource:
var dtSet = new DataSet();
da.Fill(dtSet, "Booking");
data_example.DataSource = dtSet.Tables["Booking"].DefaultView;
I have developed a functionality, where I import Excel sheet to the table. But when I upload the file and click on the button to import. The code doesn't works and gives me the below mentioned error. I tried with DataAdapter but that was also not working. Please see the error below:-
The Microsoft Office Access database engine could not find the object
'TableName'. Make sure the object exists and that you spell its
name and the path name correctly.
Also, Please see the code for your reference:-
private void ImporttoSQL(string sPath)
{
string sSourceConstr1 = string.Format(#"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=C:\AgentList.xls; Extended Properties=""Excel 8.0;HDR=YES;""", sPath);
string sSourceConstr = string.Format(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=""Excel 12.0 Xml;HDR=YES;""", sPath);
OleDbConnection sSourceConnection = new OleDbConnection(sSourceConstr);
using (sSourceConnection)
{
string sql = string.Format("Select [Merchant_Name],[Store_Name],[Store_Address],[City] FROM [MerchantTempDetail]", "Sheet1$");
OleDbCommand command = new OleDbCommand(sql, sSourceConnection);
sSourceConnection.Open();
conn.Open();
using (OleDbDataReader dr = command.ExecuteReader())
{
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(conn))
{
bulkCopy.DestinationTableName = "MerchantTempDetail";
//You can mannualy set the column mapping by the following way.
// bulkCopy.ColumnMappings.Add("Mini_Category_Id", "Mini_Category_Id");
//bulkCopy.ColumnMappings.Add("CategoryId", "CategoryId");
bulkCopy.ColumnMappings.Add("Merchant_Name", "Merchant_Name");
bulkCopy.ColumnMappings.Add("Store_Name", "Store_Name");
bulkCopy.ColumnMappings.Add("Store_Address", "Store_Address");
bulkCopy.ColumnMappings.Add("City", "City");
bulkCopy.WriteToServer(dr);
}
}
}
}
Edited code :-
public static void ExcelToSqlServerBulkCopy()
{
// Connection String to Excel Workbook
// Jet4
string excelConnectionString = #"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=AgentList.xls; Extended Properties=""Excel 8.0;HDR=YES;""";
// Ace Ole db 12
string excelAceOleDb12ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=AgentList.xls;Extended Properties=""Excel 8.0;HDR=YES;""";
// Create Connection to Excel Workbook
using (OleDbConnection connection = new OleDbConnection(excelAceOleDb12ConnectionString))
{
OleDbCommand command = new OleDbCommand("Select [Merchant_Name],[Store_Name],[Store_Address],[City] FROM [Sheet1$]", connection);
// open excel
connection.Open();
// Create DbDataReader to Data Worksheet
using (DbDataReader dr = command.ExecuteReader())
{
// SQL Server Connection String
string sqlConnectionString = ConfigurationManager.ConnectionStrings["DefaultSQLConnectionString"].ConnectionString;
// Bulk Copy to SQL Server
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(sqlConnectionString))
{
bulkCopy.DestinationTableName = "MerchantTempDetail";
bulkCopy.WriteToServer(dr);
}
}
}
}
protected void btnImport_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
string sPath = Server.MapPath(FileUpload1.FileName);
FileUpload1.SaveAs(sPath);
ExcelToSqlServerBulkCopy();
}
}
You need to define 2 connections, one for the Excel source, another for the sql database you are bulk copying to. (This code has been tested) If you need to copy to an in-memory data table, use this example on MSDN.
public static void ExcelToSqlServerBulkCopy ()
{
// Connection String to Excel Workbook
// Jet4
string excelConnectionString = #"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=AgentList.xls; Extended Properties=""Excel 8.0;HDR=YES;""";
// Ace Ole db 12
string excelAceOleDb12ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=AgentList.xls;Extended Properties=""Excel 8.0;HDR=YES;""";
// Create Connection to Excel Workbook
using (OleDbConnection connection = new OleDbConnection(excelAceOleDb12ConnectionString))
{
OleDbCommand command = new OleDbCommand("Select [Merchant_Name],[Store_Name],[Store_Address],[City] FROM [AgentList$]", connection);
// open excel
connection.Open ();
// Create DbDataReader to Data Worksheet
using (DbDataReader dr = command.ExecuteReader ())
{
// SQL Server Connection String
string sqlConnectionString = #"Data Source=.\SQLEXPRESS;Initial Catalog=StackOverflow;Integrated Security=True";
// Bulk Copy to SQL Server
using (SqlBulkCopy bulkCopy = new SqlBulkCopy (sqlConnectionString))
{
bulkCopy.DestinationTableName = "Q26382169";
bulkCopy.WriteToServer (dr);
}
}
}
}
Very important details using variable names above:
the database you are copying to (StackOverflow) must be created a priori.
the destination table (Q26382169) must exist in that database, DDL trivial, same columns as your Excel file.
Since you are using HDR=YES option, first row of Excel sheet must contain specified column names: Merchant_Name, Store_Name, Store_Address, City (without [])
The name of the sheet in the OleDbCommand (AgentList$)
Finally solved by debugging it.
private void ImporttoSQL(string sPath)
{
string sSourceConstr1 = string.Format(#"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=C:\AgentList.xls; Extended Properties=""Excel 8.0;HDR=YES;""", sPath);
string sSourceConstr = string.Format(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=""Excel 12.0 Xml;HDR=YES;""", sPath);
// string sSource = string.Format(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + sPath + ";Extended Properties=Excel 8.0", sPath);
// string sDestConstr = ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString;
OleDbConnection sSourceConnection = new OleDbConnection(sSourceConstr);
using (sSourceConnection)
{
SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DefaultSQLConnectionString"].ConnectionString);
string sql = "Select [Merchant_Name],[Store_Name],[Store_Address],[City] FROM [Sheet1$]";
OleDbCommand command = new OleDbCommand(sql, sSourceConnection);
sSourceConnection.Open();
conn.Open();
using (OleDbDataReader dr = command.ExecuteReader())
{
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(conn))
{
bulkCopy.DestinationTableName = "MerchantTempDetail";
bulkCopy.ColumnMappings.Add("Merchant_Name", "Merchant_Name");
bulkCopy.ColumnMappings.Add("Store_Name", "Store_Name");
bulkCopy.ColumnMappings.Add("Store_Address", "Store_Address");
bulkCopy.ColumnMappings.Add("City", "City");
bulkCopy.WriteToServer(dr);
}
}
}
}
I want to track how many records are saved after uploading and importing an Excel file into my SQL database. Please can someone modify my code so that it can show the number of records stored in my table as well as a 'success' or 'failure' message?
Here is my code:
protected void btnSend_Click(object sender, EventArgs e) {
//file upload path
string path = fileuploadExcel.PostedFile.FileName;
//Create connection string to Excel work book
string excelConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source='C:\Users\xxxxxx\Desktop\1-8-13-ct.xlsx';Extended Properties=Excel 12.0;Persist Security Info=False";
//Create Connection to Excel work book
OleDbConnection excelConnection =new OleDbConnection(excelConnectionString);
//Create OleDbCommand to fetch data from Excel
OleDbCommand cmd = new OleDbCommand("Select * from [Sheet1$]",excelConnection);
excelConnection.Open();
OleDbDataReader dReader;
dReader = cmd.ExecuteReader();
SqlBulkCopy sqlBulk = new SqlBulkCopy(strConnection);
//Give your Destination table name
sqlBulk.DestinationTableName = "contact";
sqlBulk.WriteToServer(dReader);
excelConnection.Close();
}
You can use a DataTable instead of a DataReader so you can predetermine the number of rows that will be written. For example:
protected void btnSend_Click(object sender, EventArgs e)
{
//file upload path
string path = fileuploadExcel.PostedFile.FileName;
//Create connection string to Excel work book
string excelConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source='C:\Users\xxxxxx\Desktop\1-8-13-ct.xlsx';Extended Properties=Excel 12.0;Persist Security Info=False";
//Create Connection to Excel work book
OleDbConnection excelConnection =new OleDbConnection(excelConnectionString);
//Create OleDbCommand to fetch data from Excel
OleDbCommand cmd = new OleDbCommand("Select * from [Sheet1$]",excelConnection);
excelConnection.Open();
OleDbDataReader dReader;
// Datatable table = new DataTable();
DataTable table = new DataTable();
dReader = cmd.ExecuteReader();
table.Load(dReader);
SqlBulkCopy sqlBulk = new SqlBulkCopy(strConnection);
//Give your Destination table name
sqlBulk.DestinationTableName = "contact";
sqlBulk.WriteToServer(table);
excelConnection.Close();
int numberOfRowsInserted= table.Rows.Count;// <-- this is what was written.
string message=string.Format("<script>alert({0});</script>",numberOfRowsInserted);
ScriptManager.RegisterStartupScript(this, this.GetType(), "scr",message , false);
}
You could achieve this by creating a new command to read the number of rows from the sheet as so:
OleDbCommand cmd1 = new OleDbCommand("select count(*) from [Sheet1$]", excelConnection);
int rows = (int)cmd1.ExecuteScalar();
Or alternatively, do the same using the target database table.
The following hack (using reflection) is an option:
/// <summary>
/// Helper class to process the SqlBulkCopy class
/// </summary>
static class SqlBulkCopyHelper
{
static FieldInfo rowsCopiedField = null;
/// <summary>
/// Gets the rows copied from the specified SqlBulkCopy object
/// </summary>
/// <param name="bulkCopy">The bulk copy.</param>
/// <returns></returns>
public static int GetRowsCopied(SqlBulkCopy bulkCopy)
{
if (rowsCopiedField == null)
{
rowsCopiedField = typeof(SqlBulkCopy).GetField("_rowsCopied", BindingFlags.NonPublic | BindingFlags.GetField | BindingFlags.Instance);
}
return (int)rowsCopiedField.GetValue(bulkCopy);
}
}
And then use the class as follows:
int rowsCopied = SqlBulkCopyHelper.GetRowsCopied(bulkCopyObjectInYourCode);
Hope this helps.
from: https://stackoverflow.com/a/4474394/1727357
I've been doing a C# project where I browse and view an Excel File into a gridview. However, there is an error message which I don't understand. Can someone please help me out on this.
This is the code I used:
private void buttonUpload_Click(object sender, EventArgs e)
{
string connectionString = String.Format(#"Data Source={0};Extended Properties=""Excel 8.0;HDR=YES;IMEX=1;""", textBoxFileName.Text);
string query = String.Format("select * from [{0}$]", "Sheet1");
SqlDataAdapter dataAdapter = new SqlDataAdapter(query, connectionString);
DataSet dataSet = new DataSet();
dataAdapter.Fill(dataSet);
dataGridView1.DataSource = dataSet.Tables[0];
}
This is the error message:
"A network-related or instance-specific error occurred while establishing
a connection to SQL Server. The server was not found or was not accessible.
Verify that the instance name is correct and that SQL Server is configured
to allow remote connections.
(provider: SQL Network Interfaces,
error: 26 - Error Locating Server/Instance Specified)."
You are trying to connect to Excel via a SqlConnection.
To connect to Excel use OleDBConnection:
private void buttonUpload_Click(object sender, EventArgs e)
{
string connectionString = String.Format(#"Data Source={0};Extended Properties=""Excel 8.0;HDR=YES;IMEX=1;""", textBoxFileName.Text)
var objConn = new OleDbConnection(connectionString);
objConn.Open();
OleDbCommand objCmdSelect = new OleDbCommand("SELECT * FROM [Sheet1$]", objConn);
OleDbDataAdapter objAdapter1 = new OleDbDataAdapter();
objAdapter1.SelectCommand = objCmdSelect;
DataSet objDataset1 = new DataSet();
objAdapter1.Fill(objDataset1);
objConn.Close();
}
You can not use SqlConnection or SqlDataAdapter for ODBC or JET connections. Use OleDbConnection or OleDbDataAdapter.
Please also make sure to dispose of connections and resources in a timely manner. Using the using statement is recommended here.
private void buttonUpload_Click(object sender, EventArgs e)
{
string connectionString = String.Format(#"Data Source={0};Extended Properties=""Excel 8.0;HDR=YES;IMEX=1;""", textBoxFileName.Text);
DataSet objDataset1 = new DataSet();
using (OleDbConnection objConn = new OleDbConnection(connectionString))
{
objConn.Open();
using (OleDbCommand objCmdSelect = new OleDbCommand("SELECT * FROM [Sheet1$]", objConn))
using (OleDbDataAdapter objAdapter1 = new OleDbDataAdapter())
{
objAdapter1.SelectCommand = objCmdSelect;
objAdapter1.Fill(objDataset1);
}
}
}