I am trying to use a method I pulled off of CodePlex, which exports data from Excel into a SQL table. I have made some minor code adjustments, but I still can't seem to get the data to import. Does anyone see anything glaringly wrong with my syntax? Thanks.
static void Main(string[] args)
{
importdatafromexcel("C:/Users/usname/Desktop/TestDirectories/FileSystemWatcher/Test_123.xlsx");
}
public static void importdatafromexcel(string excelfilepath)
{
//declare variables - edit these based on your particular situation
string ssqltable = "Name";
// 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 Name,EmployeeID from [sheet1$]";
try
{
//create our connection strings
string sexcelconnectionstring = "Provider=Microsoft.Jet.OLEDB.4.0;data source=" + excelfilepath + ";Extended Properties=" + "\"excel 8.0;hdr=yes;\"";
//MyConnection = new System.Data.OleDb.OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + excelfilepath + ";Extended Properties=Excel 8.0;HDR=YES'");
string ssqlconnectionstring = "server=DESKTOP-6CIMC97;Initial Catalog=TestDB;integrated security=true;connection reset = false";
//<add name="ProductContext" connectionString="Server=DESKTOP-6CIMC97; Initial Catalog=ProductApps; Integrated Security=True" providerName="System.Data.SqlClient" />
//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);
sqlcmd.Connection.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;
bulkcopy.WriteToServer(dr);
//while (dr.Read())
//{
// bulkcopy.WriteToServer(dr);
//}
oledbconn.Close();
}
catch (Exception ex)
{
//handle exception
}
}
The problem is here:
while (dr.Read())
{
bulkcopy.WriteToServer(dr);
}
The while (dr.Read()) block is useful if you are iterating over the results one-by-one.
But it's not you who is iterating over the results. You want the bulk copy operation to do the iterating.
Simply replace it with
bulkcopy.WriteToServer(dr);
This should work for you.
private void SaveFileToDatabase(string filePath)
{
String strConnection = "Data Source=.\\SQLEXPRESS;AttachDbFilename='C:\\Users\\Hemant\\documents\\visual studio 2010\\Projects\\CRMdata\\CRMdata\\App_Data\\Database1.mdf';Integrated Security=True;User Instance=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 [ID],[Name],[Designation] from [Sheet1$]", excelConnection))
{
excelConnection.Open();
using (OleDbDataReader dReader = cmd.ExecuteReader())
{
using(SqlBulkCopy sqlBulk = new SqlBulkCopy(strConnection))
{
//Give your Destination table name
sqlBulk.DestinationTableName = "Excel_table";
sqlBulk.WriteToServer(dReader);
}
}
}
}
}
private string GetLocalFilePath(string saveDirectory, FileUpload fileUploadControl)
{
string filePath = Path.Combine(saveDirectory, fileUploadControl.FileName);
fileUploadControl.SaveAs(filePath);
return filePath;
}
For more info, see the links below.
https://www.codeproject.com/tips/636719/import-ms-excel-data-to-sql-server-table-using-csh
http://www.c-sharpcorner.com/UploadFile/0c1bb2/inserting-excel-file-records-into-sql-server-database-using/
As you can tell, there are MANY ways to do what you want to do.
Related
I have been trying to import an excel table into my sql database. I have tried this example:
void importdata(string excelfilepath)
{
//declare variables - edit these based on your particular situation
string ssqltable = "tTableExcel";
// make sure your sheet name is correct, here sheet name is sheet1, so you can change your sheet name if have
string myexceldataquery = "select student,rollno,course from [sheet1$]";
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 = "server=mydatabaseservername;userid=dbuserid;password=dbuserpassword;database=databasename;connection reset=false";
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)
{
//handle exception
}
}
My programming is not very good and I cannot make it work.
There is nothing wrong with the SQL connection (the db is cleared after running the program). But I am not able to get any information into the database.
My excel file is called test.xlsx and is stored in D:\Users\Haners. My database tabe is called Test. How can I make my program import the information in the excel file to the database???
Previous Code :
SqlBulkCopy bulkcopy = new SqlBulkCopy(ssqlconnectionstring);
bulkcopy.DestinationTableName = ssqltable;
while (dr.Read())
{
bulkcopy.WriteToServer(dr);
}
New Code :
SqlBulkCopy bulkcopy = new SqlBulkCopy(ssqlconnectionstring);
bulkcopy.DestinationTableName = ssqltable;
bulkcopy.BatchSize=100;
bulkcopy.WriteToServer(dr);
Hope this help to resolve your issue. Happy coding. cheers
I need help with this code. I am trying to import into SQL database from excel. A column is set to unique so that if it discovers duplicate data it ignores it. In this case instead of ignoring it I want it to update the data if there is an update. Here is the code;
if (con.State == ConnectionState.Open)
{
con.Close();
}
con.Open();
if (comboBox1.SelectedItem.ToString() == "Comissioned Sites")
{
string pathConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + txtFilePath.Text + ";Extended Properties=\"Excel 12.0;HDR=Yes;\";";
// Create Connection to Excel Workbook
using (OleDbConnection connection = new OleDbConnection(pathConn))
{
OleDbCommand command = new OleDbCommand("Select * FROM [" + txtSheet.Text + "$]", connection);
connection.Open();
// Create DbDataReader to Data Worksheet
using (OleDbDataReader dr = command.ExecuteReader())
{
// Bulk Copy to SQL Server
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(con))
{
con.Open();
bulkCopy.DestinationTableName = "tblView";
bulkCopy.WriteToServer(dr);
con.Close();
}
}
}
MessageBox.Show("File Imported to Database Successfully");
}
So what you want is an upsert? Take a look at MERGE
MERGE - MSDN
How to import the data from an Excel sheet into SQL Server database in asp net?
Dim OleDbcon As New OleDbConnection((Convert.ToString("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=") & path) + ";Extended Properties=Excel 12.0;")
Dim cmd As New OleDbCommand("SELECT * FROM [Sheet1$]", OleDbcon)
Dim objAdapter1 As New OleDbDataAdapter(cmd)
OleDbcon.Open()
Dim dr As DbDataReader = cmd.ExecuteReader()
Dim con_str As String = "Data Source=.;Initial Catalog=studentdetails;Integrated Security=True"
' Bulk Copy to SQL Server
Dim bulkInsert As New SqlBulkCopy(con_str)
bulkInsert.DestinationTableName = "Table name"
bulkInsert.WriteToServer(dr)
OleDbcon.Close()e here
Break this down into two steps:
1) Save the file somewhere - it's very common to see this:
string saveFolder = #"C:\temp\uploads"; //Pick a folder on your machine to store the uploaded files
string filePath = Path.Combine(saveFolder, FileUpload1.FileName);
FileUpload1.SaveAs(filePath);
Now you have your file locally and the real work can be done.
2) Get the data from the file. Your code should work as is but you can simply write your connection string this way:
string excelConnString = String.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties="Excel 12.0";", filePath);
You can then think about deleting the file you've just uploaded and imported.
To provide a more concrete example, we can refactor your code into two methods:
private void SaveFileToDatabase(string filePath)
{
String strConnection = "Data Source=.\\SQLEXPRESS;AttachDbFilename='C:\\Users\\Hemant\\documents\\visual studio 2010\\Projects\\CRMdata\\CRMdata\\App_Data\\Database1.mdf';Integrated Security=True;User Instance=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 [ID],[Name],[Designation] from [Sheet1$]", excelConnection))
{
excelConnection.Open();
using (OleDbDataReader dReader = cmd.ExecuteReader())
{
using(SqlBulkCopy sqlBulk = new SqlBulkCopy(strConnection))
{
//Give your Destination table name
sqlBulk.DestinationTableName = "Excel_table";
sqlBulk.WriteToServer(dReader);
}
}
}
}
}
private string GetLocalFilePath(string saveDirectory, FileUpload fileUploadControl)
{
string filePath = Path.Combine(saveDirectory, fileUploadControl.FileName);
fileUploadControl.SaveAs(filePath);
return filePath;
}
You could simply then call SaveFileToDatabase(GetLocalFilePath(#"C:\temp\uploads", FileUpload1));
Consider reviewing the other Extended Properties for your Excel connection string. They come in useful!
Other improvements you might want to make include putting your Sql Database connection string into config, and adding proper exception handling. Please consider this example for demonstration only!
we will create a method data table in which we will take excel sheet info in data table or data set after that we will push that data into SQL database table using SQL bulk
protected void Button1_Click(object sender, EventArgs e)
{
try
{
SqlConnection con = new SqlConnection(#"Data
Source=SANI2711\SQLEXPRESS;Initial Catalog=customer;Integrated
Security=True;");
con.Open();
DataTable dt = new DataTable();
dt = DataExcel();
if (dt.Rows.Count > 0)
{
for()
}
}
catch(Exception ex)
{
Response.Write(ex);
}
}
protected void Button2_Click(object sender, EventArgs e)
{
try
{
SqlConnection con = new SqlConnection(#"Data
Source=SANI2711\SQLEXPRESS;Initial Catalog=customer;Integrated
Security=True;");
con.Open();
DataTable dt = new DataTable();
dt = DataExcel();
if (dt.Rows.Count > 0)
{
SqlBulkCopy objbulk = new SqlBulkCopy(con);
objbulk.DestinationTableName = "customer1";
objbulk.ColumnMappings.Add("CustomerID", "CustomerID");
objbulk.ColumnMappings.Add("City", "City");
objbulk.ColumnMappings.Add("Country", "Country");
objbulk.ColumnMappings.Add("PostalCode", "PostalCode");
objbulk.WriteToServer(dt);
}
}
catch (Exception ex)
{
Response.Write(ex);
}
}
protected DataTable DataExcel()
{
DataTable dt = new System.Data.DataTable();
try
{
string filenname=#"C:\Users\sani singh\Documents\Excel03.xls";
string sWorkbook = "[Sheet1$]";
string ExcelConnectionString=#"Provider=Microsoft.Jet.OLEDB.4.0;Data
Source="+filenname+";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'";
OleDbConnection OleDbConn = new OleDbConnection(ExcelConnectionString);
OleDbConn.Open();
OleDbCommand OleDbCmd = new OleDbCommand(("SELECT * FROM " + sWorkbook),
OleDbConn);
DataSet ds = new DataSet();
OleDbDataAdapter sda = new OleDbDataAdapter(OleDbCmd);
sda.Fill(ds);
dt = ds.Tables[0];
OleDbConn.Close();
}
catch(Exception ex)
{
Response.Write(ex);
}
return dt;
}
}
}
Add a DataTable which can hold the Excel data generated via OLEDb.
string excelconnectionstring = String.Format(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + excelfilepath + ";Excel 12.0 Xml;HDR=YES;IMEX=1;TypeGuessRows=0;ImportMixedTypes=Text;Jet OLEDB:Max Buffer Size=256;");
using (OleDbConnection oledbconn = new OleDbConnection(excelconnectionstring))
{
using (OleDbCommand oledbcmd = new OleDbCommand(myexceldataquery, oledbconn))
{
oledbconn.Open();
OleDbDataReader dr = oledbcmd.ExecuteReader();
dtBulkUpload.Load(dr);
}
}
Then serialize this DataTable to XML which can be sent to SQL Stored Proc. This approach is very useful if there are too many fields and you can send all in a single parameter
using (StringWriter strXML = new StringWriter())
{
dtBulkUpload.TableName = "BulkUpload";
dtBulkUpload.WriteXml(strXML, XmlWriteMode.IgnoreSchema, false);
xmlString = strXML.ToString();
}
using (SqlCommand cmd = new SqlCommand("Stored PROC Name"))
{
cmd.Parameters.AddWithValue("#dtBulkUpload", bulkUploadData);
//SqlParameter returnParameter = cmd.Parameters.Add("#result", SqlDbType.NVarChar);
//returnParameter.Direction = ParameterDirection.Output;
cmd.Parameters.Add("#result", SqlDbType.NVarChar,3000);
cmd.Parameters["#result"].Direction = ParameterDirection.Output;
cmd.Connection = con;
cmd.CommandType = CommandType.StoredProcedure;
con.Open();
cmd.ExecuteNonQuery();
query = (string)(cmd.Parameters["#result"].Value.ToString());
con.Close();
Am having one excel file with 2 different worksheets as fundmodelrate and project.Now I want to import these 2 different sheet values into 2 different sql tables(k2_fundmodelrate,k2_project).I can able to do import only if am working with 1 sheet and and 1 table,but I want two sheets values to be imported on two tables at the same time on button click event.
My code below:
private String strConnection = "Data Source=kuws4;Initial Catalog=jes;User ID=sa;Password=******";
protected void btnSend_Click(object sender, EventArgs e)
{
string path = fileuploadExcel.PostedFile.FileName;
string excelConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\fmr.xls;Extended Properties=Excel 12.0;Persist Security Info=False";
OleDbConnection excelConnection = new OleDbConnection(excelConnectionString);
OleDbCommand cmd = new OleDbCommand("Select * from [FundModelRate$]", excelConnection);
//OleDbCommand cmd1 = new OleDbCommand("Select * from [FundModelRate$], [Project$]", excelConnection);
excelConnection.Open();
OleDbDataReader dReader;
dReader = cmd.ExecuteReader();
SqlBulkCopy sqlBulk = new SqlBulkCopy(strConnection);
sqlBulk.DestinationTableName = "K2_FundModelRate";
// sqlBulk.DestinationTableName = "K2_Project";
sqlBulk.WriteToServer(dReader);
excelConnection.Close();
}
I think the only way is to loop through your two sheets.
Have a look at This post. This will help you get the sheet names.
When you have the sheet names, you can then just loop through them and then load them into SQL.
Maybe this can help you:
OleDbConnection objConn = null;
System.Data.DataTable dt = null;
string excelConnection = "";
if(strFile.Trim().EndsWith(".xlsx"))
{
excelConnection = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0 Xml;HDR=YES;IMEX=1\";", strFile);
}
else if(strFile.Trim().EndsWith(".xls"))
{
excelConnection = string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1\";", strFile);
}
objConn = new OleDbConnection(excelConnection);
objConn.Open();
dt = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
String[] excelSheets = new String[dt.Rows.Count];
int i = 0;
foreach(DataRow row in dt.Rows)
{
excelSheets[i] = row["TABLE_NAME"].ToString();
i++;
}
for(int j=0; j < excelSheets.Length; j++)
{
OleDbCommand cmd = new OleDbCommand("Select * from " + excelSheets[j], excelConnection);
excelConnection.Open();
OleDbDataReader dReader;
dReader = cmd.ExecuteReader();
SqlBulkCopy sqlBulk = new SqlBulkCopy(strConnection);
sqlBulk.DestinationTableName = "YourDestinationTableName";
sqlBulk.WriteToServer(dReader);
excelConnection.Close();
}
Note: Not tested
public void importdatafromexcel(string excelfilepath)
{
//declare variables - edit these based on your particular situation
string ssqltable = "test_data";//sql table name
// make sure your sheet name is correct, here sheet name is sheet1, so you can change your sheet name if havedifferent
string myexceldataquery = "select * from [Sheet1$]";
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 = "server=ServerName;user id=sa;password=sa;database=Databasename;connection reset=false";
//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);
DataTable dt = new DataTable();
bulkcopy.DestinationTableName = ssqltable;
bulkcopy.WriteToServer(dr);
oledbconn.Close();
}
catch (Exception)
{
throw;
}
}
/*---------- call that file on buttonclick through OpenDialogBox--------*/
private void button1_Click(object sender, EventArgs e)
{
DialogResult result = openFileDialog1.ShowDialog();
if (result == DialogResult.OK) // Test result.
{
string strfilename = openFileDialog1.InitialDirectory + openFileDialog1.FileName;
importdatafromexcel(strfilename);
}
Console.WriteLine(result);
MessageBox.Show("Exported to SQL successfully");
}
I am importing data from MS Excel.
The code i have written is,
var ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" +
uploadfile.PostedFile.FileName + ";" + "Extended Properties=Excel 12.0;";
OleDbConnection objConn = new OleDbConnection(sConnectionString);
objConn.Open();
try
{
var objCmdSelect = new OleDbCommand("select * from [Sheet1$]", objConn);
}
and so on.
I got an error which looks very generic to me
The Microsoft Office Access database engine could not find the object 'Sheet1$'. Make sure the object exists and that you spell its name and the path name correctly
*
My worksheet name is spelled correclty
but for my confirmation, i did below code
dt = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if(dt == null)
{
return null;
}
var excelSheets = new String[dt.Rows.Count];
int i = 0;
// Add the sheet name to the string array.
foreach(DataRow row in dt.Rows)
{
excelSheets[i] = row["TABLE_NAME"].ToString();
i++;
}
*
but i got my Data Table null.
My question is the connection is open successfully but i can't read data from the excel file.
Is there any special Authentication required.?
because i am getting the above error.
Instead if Ace.OLEDB you may try by Microsoft.Jet.OLEDB, because I faced the simillar then I switch over to Jet.OLEDB
string MyExelFile = "C:\Temp\Sample.xls";
string MyExcelSheet = "[Sheet1$]";
string StrConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + MyExelFile + ";
Extended Properties=\"Excel 8.0; HDR=Yes; IMEX=1\"";
String MySQLSelect = "select * from " + MyExcelSheet + "";
DataTable Items=new DataTable() ;
System.Data.OleDb.OleDbConnection Cn = new System.Data.OleDb.OleDbConnection();
Cn.ConnectionString = StrConn;
System.Data.OleDb.OleDbDataAdapter Da = new System.Data.OleDb.OleDbDataAdapter
(MySQLSelect, Cn);
Cn.Open();
Da.Fill(Items);
Cn.Close();
</pre>