I tried import a Excel file using c#. When I tried to import a Excel file is creating a new Excel file with same name of importing file also that new file is corrupted. I don't why this happened.
My code:
private void button1_Click(object sender, EventArgs e)
{
//database name
string table = "importing";
// Excel sheet name
string excelQuery = "select * from [Sheet1$]";
try
{
//create connection strings
string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\\New folder (2)\\importing1.xls;Extended Properties=\"Excel 8.0;HDR=Yes;\";";
string sqlConnectionstring = "Data Source=LAB-2\\SQLEXPRESS;Initial Catalog=LMS;Persist Security Info=True;User ID=smart;Password=smart";
//To clear the previous data in the database
string resetQuery = "delete from " + table;
SqlConnection connection = new SqlConnection(sqlConnectionstring);
SqlCommand cmd = new SqlCommand(resetQuery, connection);
connection.Open();
cmd.ExecuteNonQuery();
connection.Close();
//copy data from the excel file
OleDbConnection con = new OleDbConnection(connectionString);
OleDbCommand cmdOLEDB = new OleDbCommand(excelQuery, con);
con.Open();
OleDbDataReader dataReader = cmdOLEDB.ExecuteReader();
SqlBulkCopy bulkcopy = new SqlBulkCopy(sqlConnectionstring);
bulkcopy.DestinationTableName = table;
while (dataReader.Read())
{
bulkcopy.WriteToServer(dataReader);
}
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
Related
I am using the below code to import excel data into DB table. The code works fine in my local and when I move this code to server the import fails in between. Also I don't get any error messages and I get a message data saved successfully.
For Ex: The excel has 75,000 data's and only 13,500 records are getting inserted and the size of the excel file is 5 MB.
Any suggestions about the possible problems?
CS:
protected void btnImportData_Click(object sender, EventArgs e)
{
try
{
string strCS = string.Empty; ;
string strFileType = Path.GetExtension(FileUploadExcel.FileName).ToLower();
string query = "";
lblError.Text = "";
string FileName = string.Empty;
FileName = Path.GetFileName(FileUploadExcel.PostedFile.FileName);
string Extension = Path.GetExtension(FileUploadExcel.PostedFile.FileName);
string FolderPath = ConfigurationManager.AppSettings["FolderPath"];
string path = Path.GetFileName(Server.MapPath(FileUploadExcel.FileName));
System.IO.File.Delete(Server.MapPath(FolderPath) + path);
FileUploadExcel.SaveAs(Server.MapPath(FolderPath) + path);
string filePath = Server.MapPath(FolderPath) + path;
if (strFileType != String.Empty)
{
if (strFileType.Trim() == ".xls")
{
strCS = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";
}
else if (strFileType.Trim() == ".xlsx")
{
strCS = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
}
else
{
ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Please upload the correct file format')", true);
return;
}
try
{
OleDbConnection conn = new OleDbConnection(strCS);
if (conn.State == ConnectionState.Closed)
conn.Open();
System.Data.DataTable dt = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
string sheetname = dt.Rows[0]["Table_Name"].ToString();
query = "SELECT * FROM [" + sheetname + "]";
OleDbCommand cmd = new OleDbCommand(query, conn);
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
if (conn.State == ConnectionState.Open)
{
conn.Close();
conn = null;
}
string strSqlTable = "TABLENAME";
string sclearsql = "delete from " + strSqlTable;
SqlConnection sqlconn = new SqlConnection(strCon);
SqlCommand sqlcmd = new SqlCommand(sclearsql, sqlconn);
sqlconn.Open();
sqlcmd.ExecuteNonQuery();
sqlconn.Close();
OleDbConnection oledbconn = new OleDbConnection(strCS);
oledbconn.Open();
OleDbCommand oledbcmd = new OleDbCommand(query, oledbconn);
oledbcmd.CommandTimeout = 120;
OleDbDataReader dReader = oledbcmd.ExecuteReader();
SqlBulkCopy bulkCopy = new SqlBulkCopy(strCon);
bulkCopy.DestinationTableName = strSqlTable;
bulkCopy.BulkCopyTimeout = 120;
bulkCopy.BatchSize = 1000;
bulkCopy.WriteToServer(dReader);
oledbconn.Close();
ClientScript.RegisterStartupScript(Page.GetType(), "alert", "alert('Data saved successfully');window.location='Panel.aspx';", true);
}
catch (Exception ex)
{
lblError.Text = "Upload status: The file could not be uploaded due to following reasons.Please check: " + ex.Message;
}
}
else
{
ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Please select a file to import the data.')", true);
}
}
catch (Exception ex)
{
lblError.Text = "Upload status: The file could not be uploaded due to following reasons.Please check: " + ex.Message;
}
}
Hi remove the data reader on you code which read the excel file twice and use the dataset to fill out your SQL table:
See below:
DataTable dtexcel = new DataTable();
using (OleDbConnection conn = new OleDbConnection(strCS))
{
conn.Open();
DataTable schemaTable = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
//Looping a first Sheet of Xl File
DataRow schemaRow = schemaTable.Rows[0];
string sheet = schemaRow["TABLE_NAME"].ToString();
if (!sheet.EndsWith("_"))
{
string query = "SELECT * FROM [" + sheet + "]";
OleDbDataAdapter daexcel = new OleDbDataAdapter(query, conn);
dtexcel.Locale = CultureInfo.CurrentCulture;
daexcel.Fill(dtexcel);
}
}
using (SqlConnection sqlconn = new SqlConnection(strCon))
{
SqlCommand sqlcmd = new SqlCommand(sclearsql, sqlconn);
sqlconn.Open();
sqlcmd.ExecuteNonQuery();
}
using (SqlConnection sqlconn = new SqlConnection(strCon))
{
using (SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(sqlconn))
{
//Set the database table name
sqlBulkCopy.DestinationTableName = strSqlTable;
sqlconn.Open();
sqlBulkCopy.WriteToServer(dtexcel);
}
}
Have you tried using the dts wizard? it is a nice tool if you have a excel sheet with data.
you use it by opening the command prompt. windowsbutton + r, and the write cmd.
and from in here you write dtswizard
then a wizard opens in a new window where you can select the excel sheet that you want to insert. There is many tutorials on google.
Hope you can use this
Below is my code, any help will be greatly appreciated
:The Microsoft Office Access database engine could not find the object 'Breach'. Make sure the object exists and that you spell its name and the path name correctly.
public void importdatafromexcel(string excelfilepath)
{
string ssqltable = "Testing";
string myexceldataquery = "select [Case Owner],[Case Number],[Severity] from [Breach]";
try
{
string sexcelconnectionstring = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + excelfilepath + ";Extended Properties=Excel 12.0;";
string ssqlconnectionstring = "Persist Security Info=False;Integrated Security=true;Initial Catalog=0Breach;server= CHAUDAHARI-J1-W\\SQLEXPRESS";
string sclearsql = "delete from " + ssqltable;
SqlConnection sqlconn = new SqlConnection(ssqlconnectionstring);
SqlCommand sqlcmd = new SqlCommand(sclearsql, sqlconn);
sqlconn.Open();
sqlcmd.ExecuteNonQuery();
sqlconn.Close();
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)
{
txtProcessingStatus.Text = ex.Message;
}
}
select [Case Owner],[Case Number],[Severity] from [Breach]
Is there a worksheet named "Breach" in the Excel file you are opening? In your statement above, I believe [Breach] should be the name of the worksheet you are looking for in the Excel file you are opening.
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 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);
}
}
}
}
protected void btnup_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
if (System.IO.Path.GetExtension(FileUpload1.FileName) == ".xls" || System.IO.Path.GetExtension(FileUpload1.FileName) == ".xlsx")
{
FileUpload1.SaveAs(Server.MapPath("~/Excal/sample.xlsx"));
}
}
}
protected void Button2_Click(object sender, EventArgs e)
{
string sSourceConstr = #"Provider=Microsoft.ACE.OLEDB.12.0; Data Source=C:\sample.xlsx; Extended Properties=""Excel 12.0;HDR=YES;""";
string sDestConstr = ConfigurationManager.ConnectionStrings["TestConnection"].ConnectionString;
OleDbConnection sSourceConnection = new OleDbConnection(sSourceConstr);
using (sSourceConnection)
{
string sql = string.Format("Select [ID],[Name],[Designation] FROM [{0}]", "sample$");
OleDbCommand command = new OleDbCommand(sql, sSourceConnection);
sSourceConnection.Open();
using (OleDbDataReader dr = command.ExecuteReader())
{
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(sDestConstr))
{
bulkCopy.DestinationTableName = "rr";
//You can mannualy set the column mapping by the following way.
//bulkCopy.ColumnMappings.Add("MSISDN", "MSISDN");
bulkCopy.WriteToServer(dr);
}
}
}
lblmsg.Text = "Record update";
}
I have done that before few day. Below code works for me ..
try
{
string excelConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;" +
"Data Source=" + Path of File + ";" +
#"Extended Properties=""Excel 12.0 Xml;HDR=Yes""";
//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);
sqlBulk.DestinationTableName = "ExcelTable"; // write your table name
//sqlBulk.ColumnMappings.Add("ID", "ID");
//sqlBulk.ColumnMappings.Add("Name", "Name");
sqlBulk.WriteToServer(dReader);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}