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);
}
}
}
}
Related
I want to insert excel data to sql, but excel column names are changing frequently.
Below is the code I have written for excel bulk upload
string excelConnectionString = string.Format(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=""Excel 12.0 Xml;HDR=YES""", path);
//// Create Connection to Excel Workbook
{
string destablename1 = string.Empty;
destablename1 = "[admin.AttendanceData]";
DataTable Data = new DataTable();
using (OleDbConnection conn = new OleDbConnection(excelConnectionString))
{
conn.Open();
OleDbCommand cmd = new OleDbCommand(#"SELECT * FROM [Attendance$]", conn);
OleDbDataAdapter adapter = new OleDbDataAdapter(cmd);
adapter.Fill(Data);
conn.Close();
}
var dacObj = new DAC();
String strConnection = System.Configuration.ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(strConnection))
{
bulkCopy.ColumnMappings.Add("Emp ID", "Citrix_ID");
bulkCopy.ColumnMappings.Add("Full Name", "Full_Name");
bulkCopy.ColumnMappings.Add("Band", "Band");
bulkCopy.ColumnMappings.Add("Cigna DOJ", "Cigna_DOJ");
bulkCopy.DestinationTableName = destablename1;
dacObj.OpenConnection();
bulkCopy.WriteToServer(Data);
dacObj.CloseConnection();
}
}n
how to add dynamic column names from excel to sql?
sample picture of excel sheet data
Here after Cigna DOJ columns will change for every month.
The below written code working fine for insert a table and its value in Already existing excel file(D:\MySamplefile.xls).
private void WriteToExcel()
{
string connectionString = "Provider=Microsoft.Jet.OleDb.4.0; Data Source=D:\\MySamplefile.xls; Extended Properties=Excel 8.0;";
using (OleDbConnection Connection = new OleDbConnection(connectionString))
{
Connection.Open();
using (OleDbCommand command = new OleDbCommand())
{
command.Connection = Connection;
command.CommandText = "CREATE TABLE [EMPLOYEE](EmpFirstName Char(100), EmpLastName char(100), EmpDept char(250))";
command.ExecuteNonQuery();
}
//Add values to the table (EMPTable) in the Worksheet
string strSql = "INSERT INTO EMPLOYEE (EmpFirstName, EmpLastName, [EmpDept]) VALUES (?, ?, ?)";
using (OleDbCommand dbCmd = new OleDbCommand(strSql, Connection))
{
dbCmd.CommandType = CommandType.Text;
dbCmd.Parameters.AddWithValue("EmpFirstName", "xyz");
dbCmd.Parameters.AddWithValue("EmpLastName", "abc");
dbCmd.Parameters.AddWithValue("[EmpDept]", "pqr");
dbCmd.ExecuteNonQuery();
}
}
}
My requirement is that, I need to write the same thing on a newly created excel worksheet, which not saved any where.For new excel doc creation code given below.
public void createExcelDoc( int rowHeight,int sizeCol1, int sizeCol2)
{
app = new Application();
app.Visible = true;
workbook = app.Workbooks.Add(1);
worksheet = (Worksheet)workbook.Sheets[1];
worksheet.Columns[1].ColumnWidth = 5;
worksheet.Rows.RowHeight = rowHeight;
worksheet.Columns[2].ColumnWidth = sizeCol1;
worksheet.Columns[3].ColumnWidth = sizeCol2;
workbook.Windows.Application.WindowState = XlWindowState.xlMaximized;
}
I need to replace connectionString in WriteToExcel() method Data Source=D:\\MySamplefile.xls; to some thing else. I have no idea.
You can connect to Excel via OleDb, just like with Access. Connection string examples can be found here:
https://www.connectionstrings.com/excel/
For clarity, an old (.xls) file would look like this:
string connectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;" +
#"Data Source=D:\MySamplefile.xls;Extended Properties=Excel 8.0;";
HOWEVER, it this does seem a little overkill for what your method is doing. Where is the data coming from what you're inserting into Excel? There may be better (and simpler) ways to do this.
This code is working fine on localhost but when I try to run this code in server its not working..can anyone tell me what's wrong?
private void SaveFileToDatabase(string filePath)
{
String strConnection = "Data Source=.;Initial Catalog=EkkiDB;Integrated Security=TRUE";
String excelConnString = String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0\"", filePath);
//Create Connection to Excel work book
using (OleDbConnection excelConnection = new OleDbConnection(excelConnString))
{
//Create OleDbCommand to fetch data from Excel
using (OleDbCommand cmd = new OleDbCommand("Select [SurveyDate],[DealerName],[Model],[HP],[Quantity],[ID] from [Sheet1$]", excelConnection))
{
excelConnection.Open();
using (OleDbDataReader dReader = cmd.ExecuteReader())
{
using (SqlBulkCopy sqlBulk = new SqlBulkCopy(strConnection))
{
//Give your Destination table name
sqlBulk.DestinationTableName = "Import_Survey";
sqlBulk.WriteToServer(dReader);
}
}
}
}
}
private string GetLocalFilePath( FileUpload fileUploadControl)
{
//string filePath = Server.MapPath(fileUploadControl.FileName);
// string filePath = Path.Combine(saveDirectory);
string filePath = Server.MapPath("~/xl/") + Path.GetFileName(fileUploadControl.PostedFile.FileName);
fileUploadControl.SaveAs(filePath);
return filePath;
}
Where is your destination directory? If it's not under IIS control check that your anonymous user account has write access to it.
I am trying to create an Excel data uploader to upload Excel files to SQL Server using Winforms in C#.
After bulkcopy.WriteToServer(dr); I get this error :
Multiple-step OLE DB operation generated errors. Check each OLE DB status value, if available. No work was done.
The Connection for viewing your linked Microsoft Excel worksheet was lost.
I got information about regedit here and tried to follow it but still the same error:
class Pass
{
static string _excelfilepath;
public static string excelfilepath { get { return _excelfilepath; } set { _excelfilepath = value; } }
public void importdatafromexcel()
{
//declare variables - edit these based on your particular situation
string ssqltable = "tStudent";
// make sure your sheet name is correct, here sheet name is sheet1, so you can change your sheet name if have different
string myexceldataquery = "select idnum,fname,gname,mname,coacro,year,yrstat,sex,stat,telno,addr1,addr2,addr3,dbirth,mothname,fathname,civstat,religion,hssch from [masterlist$]";
try
{
//create our connection strings
string sexcelconnectionstring = #"provider=microsoft.jet.oledb.4.0;data source=" + _excelfilepath +
";extended properties=" + "\"excel 8.0;hdr=yes;\"";
string ssqlconnectionstring = #"Data Source=LYNDON-PC\LYNDON;Initial Catalog=trial;Persist Security Info=True;User ID=sa;Password=14323531";
//execute a query to erase any previous data from our destination table
string sclearsql = "delete from " + ssqltable;
SqlConnection sqlconn = new SqlConnection(ssqlconnectionstring);
SqlCommand sqlcmd = new SqlCommand(sclearsql, sqlconn);
sqlconn.Open();
sqlcmd.ExecuteNonQuery();
sqlconn.Close();
//series of commands to bulk copy data from the excel file into our sql table
OleDbConnection oledbconn = new OleDbConnection(sexcelconnectionstring);
OleDbCommand oledbcmd = new OleDbCommand(myexceldataquery, oledbconn);
oledbconn.Open();
OleDbDataReader dr = oledbcmd.ExecuteReader();
SqlBulkCopy bulkcopy = new SqlBulkCopy(ssqlconnectionstring);
bulkcopy.DestinationTableName = ssqltable;
while (dr.Read())
{
bulkcopy.WriteToServer(dr);
}
oledbconn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
What does the error mean and get the code to upload my Excel file to my table in my database in SQL Server...
I think you should use
bulkcopy.WriteToServer(dr);
instead of using
while (dr.Read())
{
bulkcopy.WriteToServer(dr);
}
I want to import data from an Excel 2003 file, but my C# program gives error
External table is not in the expected format
I use this code:
string ExcelContentType = "application/vnd.ms-excel";
string Excel2010ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
if (fileuploadExcel.HasFile)
{
//Check the Content Type of the file
if (fileuploadExcel.PostedFile.ContentType == ExcelContentType || fileuploadExcel.PostedFile.ContentType == Excel2010ContentType)
{
try
{
//Save file path
string path = string.Concat(Server.MapPath("~/TempFiles/"), fileuploadExcel.FileName);
//Save File as Temp then you can delete it if you want
fileuploadExcel.SaveAs(path);
string excelConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1\"";
// Create Connection to Excel Workbook
using (OleDbConnection connection = new OleDbConnection(excelConnectionString))
{
OleDbCommand command = new OleDbCommand("Select * FROM [Sheet1$]", connection);
connection.Open();
// Create DbDataReader to Data Worksheet
using (DbDataReader dr = command.ExecuteReader())
{
// SQL Server Connection String
string sqlConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString.ToString();
// Bulk Copy to SQL Server
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(sqlConnectionString))
{
bulkCopy.DestinationTableName = "Excel_table";
bulkCopy.WriteToServer(dr);
lblMessage.Text = "The data has been exported succefuly from Excel to SQL";
}
}
}
}
catch (Exception ex)
{
lblMessage.Text = ex.Message;
}
}
}
Hi here i am using this to import from Excel File.Try this.Works 100%...
Here you should have a folder inside your application named as "Files" where after uploading your excel file,it will be stored and your program will read from the excel file available inside "Files" Folder.
protected void btnImport_Click(object sender, EventArgs e)
{
ArrayList alist = new ArrayList();
string connString = "";
string strFileType = Path.GetExtension(fileuploadExcel.FileName).ToLower();
string fileBasePath = Server.MapPath("~/Files/");
string fileName = Path.GetFileName(this.fileuploadExcel.FileName);
string fullFilePath = fileBasePath + fileName;
//Connection String to Excel Workbook
if (strFileType.Trim() == ".xls")
{
connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fullFilePath +
";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1\"";
}
else if (strFileType.Trim() == ".xlsx")
{
connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fullFilePath +
";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=1\"";
}
if (fileuploadExcel.HasFile)
{
string query = "SELECT [UserName],[Education],[Location] FROM [Sheet1$]";
using(OleDbConnection conn = new OleDbConnection(connString))
{
if (conn.State == ConnectionState.Closed)
conn.Open();
OleDbCommand cmd = new OleDbCommand(query, conn);
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
Session["griddata"] = ds.Tables[0];
grvExcelData.DataSource = Session["griddata"];
grvExcelData.DataBind();
}
}
}
Try this: Connection String
string connStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=Excel 12.0;";
You can use SSIS tool( Sql server integration services)
create connection to excel sheet then add source and destination
your source will be excel sheet and your destination will be Database table
ok?
if you need more info please tell me...