Unable to compare the columns in SqlBulkCopy - c#

Here is my code:
protected void Button1_Click(object sender, EventArgs e)
{
string strFileType = System.IO.Path.GetExtension(FileUpload1.FileName).ToString().ToLower();
string strFileName = FileUpload1.PostedFile.FileName.ToString();
FileUpload1.SaveAs(Server.MapPath("~/Import/" + strFileName + strFileType));
string strNewPath = Server.MapPath("~/Import/" + strFileName + strFileType);
string excelConnectionString = String.Format(#"Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source="+strNewPath +"; Extended Properties=Excel 8.0;");
//string excelConnectionString = String.Format(#"Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=C:\\myFolder\\Book1.xls;" + "Extended Properties=Excel 8.0;");
// Create Connection to Excel Workbook
using (OleDbConnection connection = new OleDbConnection(excelConnectionString))
{
OleDbCommand command = new OleDbCommand("Select ID,Data FROM [Sheet1$]", connection);
connection.Open();
// Create DbDataReader to Data Worksheet
using (DbDataReader dr = command.ExecuteReader())
{
// SQL Server Connection String
string sqlConnectionString = "Data Source=DITSEC3;Initial Catalog=test;Integrated Security=True";
con.Open();
DataTable dt1 = new DataTable();
string s = "select count(*) from ExcelTable";
string r = "";
SqlCommand cmd1 = new SqlCommand(s, con);
try
{
SqlDataAdapter da1 = new SqlDataAdapter(cmd1);
da1.Fill(dt1);
}
catch { }
int RecordCount;
RecordCount = Convert.ToInt32(cmd1.ExecuteScalar());
r = RecordCount.ToString();
Label1.Text = r;
con.Close();
int prv = Convert.ToInt32(r);
//matching columns
//SqlBulkCopyColumnMapping mapping1 = new SqlBulkCopyColumnMapping("id", "ida");
//SqlBulkCopyColumnMapping mapping2 = new SqlBulkCopyColumnMapping("data", "dataa");
// Bulk Copy to SQL Server
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(sqlConnectionString))
{
bulkCopy.DestinationTableName = "ExcelTable";
bulkCopy.WriteToServer(dr);
}
con.Open();
DataTable dt = new DataTable();
s = "select count(*) from ExcelTable"; r = "";
SqlCommand cmd = new SqlCommand(s, con);
try
{
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
}
catch { }
RecordCount = Convert.ToInt32(cmd.ExecuteScalar());
r = RecordCount.ToString(); Label1.Text = r;
con.Close();
int ltr = Convert.ToInt32(r);
if (prv == ltr)
{
Label1.Text = "No records Added";
}
else
{
Label1.Text = "Records Added Successfully !";
}
}
}
I know I need to add something like:
SqlBulkCopyColumnMapping mapping1 = new SqlBulkCopyColumnMapping("id", "ida");
SqlBulkCopyColumnMapping mapping2 = new SqlBulkCopyColumnMapping("data", "dataa");
but I am not sure where I am supposed to add it in the above code

The column mappings are to be added to the bulkCopy.ColumnsMappings collection:
var mapping1 = new SqlBulkCopyColumnMapping("id", "ida");
bulkCopy.ColumnMappings.Add(mapping1);
You do the mapping before you execute the WriteToServer call.
The MSDN documentation of SqlBulkCopyColumnMapping has further documentation and an example.

Related

How do i get data from multiple access tables into a C# windows form?

I am trying to display data from four different database tables using the code below, this method works perfectly for one table but i cant get my head around making it work for multiple, here is the code:
private void Assign_Load(object sender, EventArgs e)
{
try
{
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = ConnectionDetail.Warehouse;
string sql = "Select * from [Location], [Assign], [Products], [staff]";
da = new OleDbDataAdapter(sql, conn);
da.Fill(dt); // filling the database information into databtable
//Location Table
DataRow dr = dt.Rows[currentRow]; // counting the rows
txtLocID.Text = dr["Location ID"].ToString();
txtAisle.Text = dr["Aisle Code"].ToString();
txtSection.Text = dr["Section"].ToString();
txtShelf.Text = dr["Shelf"].ToString();
txtLocation.Text = dr["Location"].ToString();
txtLength.Text = dr["Length"].ToString();
txtWidth.Text = dr["Width"].ToString();
lstSize.Text = dr["Size Description"].ToString();
//Product Table
txtSKU.Text = dr["SKU"].ToString();
txtDes.Text = dr["Description"].ToString();
listHaz.Text = dr["Hazardous"].ToString();
listLiq.Text = dr["Liquid"].ToString();
txtQuan.Text = dr["Quantity"].ToString();
txtWeig.Text = dr["Weight"].ToString();
lstSize.Text = dr["Size Description"].ToString();
//Satff Table
txtID.Text = dr["StaffID"].ToString();
//Assign Table
txtAssID.Text = dr["Assign ID"].ToString();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
{
OleDbConnection load = new OleDbConnection();
load.ConnectionString = ConnectionDetail.Warehouse;
OleDbCommand cmds = new OleDbCommand();
lbltime.Text = DateTime.Now.ToString("yyyy MMM ddd HH:mm");
try
{
load.Open();
cmds = new OleDbCommand();
cmds.CommandText = "SELECT * FROM [Location], [Assign], [Products], [staff];";
cmds.Connection = load;
dr = cmds.ExecuteReader();
}
catch (Exception err)
{
//Any database errors jump here and output error message
MessageBox.Show("A database error has occurred: " + Environment.NewLine + err.Message);
}
finally
{
// btnNext_Click(sender, e);
txtLocID.Visible = false;
}
}
}
The best answer, is to update your SQL statement to use a JOIN statement. Assuming your data / tables are somehow related.
Else, the other way to do it, is to create separate functions to populate each set of Text items separately.
Looking at your code, I'm betting you should consider "binding".
Figured it out, this works just as well as all your suggestions, thanks for everyone's help anyway.
OleDbConnection Cons = new OleDbConnection(); // new connection
OleDbDataReader dr;
int currentRow = 0;
//Location
DataTable dt = new DataTable();
OleDbDataAdapter da;
//Product
DataTable dt1 = new DataTable();
OleDbDataAdapter da1;
//staff
DataTable dt2 = new DataTable();
OleDbDataAdapter da2;
//Assign
DataTable dt3 = new DataTable();
OleDbDataAdapter da3;
private void Assign_Load(object sender, EventArgs e)
{
try
{
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = ConnectionDetail.Warehouse;
string sql = "Select * from Location";
da = new OleDbDataAdapter(sql, conn);
da.Fill(dt); // filling the database information into databtable
//Location Table
DataRow dr = dt.Rows[currentRow]; // counting the rows
txtLocID.Text = dr["Location ID"].ToString();
txtAisle.Text = dr["Aisle Code"].ToString();
txtSection.Text = dr["Section"].ToString();
txtShelf.Text = dr["Shelf"].ToString();
txtLocation.Text = dr["Location"].ToString();
txtLength.Text = dr["Length"].ToString();
txtWidth.Text = dr["Width"].ToString();
lstSize.Text = dr["Size Description"].ToString();
//Product Table
OleDbConnection conn1 = new OleDbConnection();
conn1.ConnectionString = ConnectionDetail.Warehouse;
string sql1 = "Select * from Products";
da1 = new OleDbDataAdapter(sql1, conn1);
da1.Fill(dt1); // filling the database information into databtable
DataRow dr1 = dt1.Rows[currentRow]; // counting the rows
txtSKU.Text = dr1["SKU"].ToString();
txtDes.Text = dr1["Description"].ToString();
listHaz.Text = dr1["Hazardous"].ToString();
listLiq.Text = dr1["Liquid"].ToString();
txtQuan.Text = dr1["Quantity"].ToString();
txtWeig.Text = dr1["Weight"].ToString();
lstSize1.Text = dr1["Size Description"].ToString();
//Staff Table
OleDbConnection conn2 = new OleDbConnection();
conn2.ConnectionString = ConnectionDetail.Warehouse;
string sql2 = "Select * from Staff";
da2 = new OleDbDataAdapter(sql2, conn2);
da2.Fill(dt2); // filling the database information into databtable
DataRow dr2 = dt2.Rows[currentRow]; // counting the rows
txtID.Text = dr2["StaffID"].ToString();
//Assign Table
OleDbConnection conn3 = new OleDbConnection();
conn3.ConnectionString = ConnectionDetail.Warehouse;
string sql3 = "Select * from Assign";
da3 = new OleDbDataAdapter(sql3, conn3);
da3.Fill(dt3); // filling the database information into databtable
DataRow dr3 = dt3.Rows[currentRow]; // counting the rows
txtAssID.Text = dr3["Assign ID"].ToString();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
{
OleDbConnection load = new OleDbConnection();
load.ConnectionString = ConnectionDetail.Warehouse;
OleDbCommand cmds = new OleDbCommand();
lbltime.Text = DateTime.Now.ToString("yyyy MMM ddd HH:mm");
try
{
load.Open();
cmds = new OleDbCommand();
cmds.CommandText = "SELECT * FROM Location;";
cmds.CommandText = "SELECT * FROM Products;";
cmds.CommandText = "SELECT * FROM Staff;";
cmds.CommandText = "SELECT * FROM Assign;";
cmds.Connection = load;
dr = cmds.ExecuteReader();
}
catch (Exception err)
{
//Any database errors jump here and output error message
MessageBox.Show("A database error has occurred: " + Environment.NewLine + err.Message);
}
finally
{
// btnNext_Click(sender, e);
txtLocID.Visible = false;
}
}
}

How I can manage to fill listview with .dbf

I'm trying to open .dbf via c# wpf and load it into a ListView, but I have no luck.
In my ViewModel:
public void DBF()
{
var databasePath = #"C:\Users\jesson\Desktop\FLCOLU_Building_Outline_Hints_308EL_section3_2180ER_QC.dbf";
var connectionString = string.Format("DSN=dBase Files", databasePath);
OdbcConnection connection = new OdbcConnection(connectionString);
connection.Open();
var _command = connection.CreateCommand();
var query = string.Format(#"SELECT * FROM C:\Users\jesson\Desktop\FLCOLU_Building_Outline_Hints_308EL_section3_2180ER_QC.dbf");
string commandText = query;
var _dataAdapter = new OdbcDataAdapter(commandText, connection);
DataSet _dataSet = new DataSet();
DataTable _dataTable = new DataTable();
_dataSet.Reset();
_dataAdapter.Fill(_dataSet);
_dataTable = _dataSet.Tables[0];
var rows = _dataTable.Rows;
string userName = rows[0].ItemArray[1] as string;
string password = rows[0].ItemArray[2] as string;
UserDataVar = new InputDataSingle
{
UserName = userName,
Password = password
};
connection.Close();
}
Did I do something wrong? Any other ideas?
here you go. try below one.
string filename= //yourfilePath;
string constr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source="+ filename +";Extended Properties=dBASE IV;User ID=Admin;Password=;";
DataTable dt = new DataTable();
using (OleDbConnection con = new OleDbConnection(constr))
{
var sql = "select * from " + filename ;
OleDbCommand cmd = new OleDbCommand(sql, con);
con.Open();
DataSet ds = new DataSet(); ;
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
da.Fill(ds);
dt =ds.Tables[0]
}
here how to pass data to listview or dataGrid.;
mylistview.ItemsSource = dt.DefaultView;
Condition
you have to create View to your ListView;

How to compare excel value using asp.net SqlBulkCopy?

I am importing an Excel sheet into a SQL Server database. The Excel sheet contains 3 columns
id|data|passport
I am using SqlBulkCopy
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["constr"].ConnectionString);
string[] filePaths = null;
string strFileType = null;
string strFileName = null;
string strNewPath = null;
int fileSize;
int flag=0;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click1(object sender, EventArgs e)
{
strFileType = System.IO.Path.GetExtension(FileUpload1.FileName).ToString().ToLower();
strFileName = FileUpload1.PostedFile.FileName.ToString();
FileUpload1.SaveAs(Server.MapPath("~/Import/" + strFileName + strFileType));
strNewPath = Server.MapPath("~/Import/" + strFileName + strFileType);
fileSize = FileUpload1.PostedFile.ContentLength / 1024;
//EXCEL DETAILS TABLE
con.Open();
//=========================================
DataTable dt8 = new DataTable();
SqlCommand cmd8 = new SqlCommand("insert into exceldetails (name,type,details,size)" + "values(#name,#type,#details,#size)", con);
cmd8.Parameters.Add("#name", SqlDbType.VarChar).Value = strFileName;
cmd8.Parameters.Add("#type", SqlDbType.VarChar).Value = strFileType;
cmd8.Parameters.Add("#details", SqlDbType.VarChar).Value = DateTime.Now;
cmd8.Parameters.Add("#size", SqlDbType.Int).Value = fileSize;
cmd8.ExecuteNonQuery();
con.Close();
try
{
SqlDataAdapter da8 = new SqlDataAdapter(cmd8);
da8.Fill(dt8);
}
catch { }
//=========================================
//CHOOSING EXCEL CONNECTIONSTRING
string excelConnectionString = "";
switch (strFileType)
{
case ".xls":
excelConnectionString = String.Format(#"Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + strNewPath + "; Extended Properties=Excel 8.0;");
break;
case ".xlsx":
{
excelConnectionString = String.Format(#"Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + strNewPath + "; Extended Properties=Excel 12.0 Xml;");
break;
}
}
//===================================
//PRE EXCEL COUNT
// Create Connection to Excel Workbook
using (OleDbConnection connection = new OleDbConnection(excelConnectionString))
{
connection.Open();
OleDbCommand command = new OleDbCommand("Select ID,Data,passport FROM [Sheet1$]", connection);
OleDbCommand command1 = new OleDbCommand("select count(*) from [Sheet1$]", connection);
//Sql Server Table DataTable
DataTable dt4 = new DataTable();
SqlCommand cmd4 = new SqlCommand("select * from excelsheet", con);
try
{
SqlDataAdapter da4 = new SqlDataAdapter(cmd4);
da4.Fill(dt4);//sql table datatable
}
catch { }
//===============================
//excelsheet datatable
DataTable oltlb = new DataTable();
OleDbCommand olcmd = new OleDbCommand("select * from [Sheet1$]", connection);
try
{
OleDbDataAdapter olda = new OleDbDataAdapter(olcmd);
olda.Fill(oltlb); //excel table datatable
}
catch { }
//==============================
using (DbDataReader dr = command.ExecuteReader())
{
// SQL Server Connection String
string sqlConnectionString = "Data Source=DITSEC3;Initial Catalog=test;Integrated Security=True";
con.Open();
DataTable dt7 = new DataTable();
dt7.Load(dr);
DataRow[] ExcelRows = new DataRow[dt7.Rows.Count];
DataColumn[] ExcelColumn = new DataColumn[dt7.Columns.Count];
//=================================================
for (int i1 = 0; i1 < ExcelRows.Length; i1++)
{
string a = ExcelRows[i1]["passport"].ToString();
char a1 = a[0];
if (a1 >= 'A' || a1 <= 'Z')
{
Label12.Text = "CAPITAL";
break;
}
else
{
Label12.Text = "notgood";
flag = flag + 1;
}
}
//=========================================================
if (flag == 0)
{
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(sqlConnectionString))
{
bulkCopy.DestinationTableName = "ExcelTable";
dt7.Rows.CopyTo(ExcelRows, 0);
//==========================================================================================
for (int i = 0; i < ExcelRows.Length; i++)
{
if (ExcelRows[i]["passport"] == DBNull.Value)
{
ExcelRows[i]["passport"] = 0;
}
}
bulkCopy.WriteToServer(ExcelRows);
//==========================================================================================
for (int i = 0; i < ExcelRows.Length; i++)
{
if (ExcelRows[i]["data"] == DBNull.Value)
{
// Include any actions to perform if there is no date
//ExcelRows[i]["data"] = Convert.ToDateTime("0");
}
else
{
DateTime oldDate = Convert.ToDateTime(ExcelRows[i]["data"]).Date;
DateTime newDate = Convert.ToDateTime(oldDate).Date;
ExcelRows[i]["data"] = newDate.ToString("yyyy/MM/dd");
}
}
//==========================================================================================
}
//======
}
else
{
Label13.Text = "Wrong Format";
}
}
}
}
}
ERROR AT :
string a = ExcelRows[i1]["passport"].ToString();
ERROR:
Object reference not set to an instance of an object.

Error with SqlBulkCopyColumnMapping

I am able to import excel sheet data into sql server table but i am unable to implement column mapping. please help.
protected void Button1_Click(object sender, EventArgs e)
{
string strFileType = System.IO.Path.GetExtension(FileUpload1.FileName).ToString().ToLower();
string strFileName = FileUpload1.PostedFile.FileName.ToString();
FileUpload1.SaveAs(Server.MapPath("~/Import/" + strFileName + strFileType));
string strNewPath = Server.MapPath("~/Import/" + strFileName + strFileType);
string excelConnectionString = String.Format(#"Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source="+strNewPath +"; Extended Properties=Excel 8.0;");
//string excelConnectionString = String.Format(#"Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=C:\\myFolder\\Book1.xls;" + "Extended Properties=Excel 8.0;");
// Create Connection to Excel Workbook
using (OleDbConnection connection = new OleDbConnection(excelConnectionString))
{
OleDbCommand command = new OleDbCommand("Select ID,Data FROM [Sheet1$]", connection);
connection.Open();
// Create DbDataReader to Data Worksheet
using (DbDataReader dr = command.ExecuteReader())
{
// SQL Server Connection String
string sqlConnectionString = "Data Source=DITSEC3;Initial Catalog=test;Integrated Security=True";
con.Open();
DataTable dt1 = new DataTable();
string s = "select count(*) from ExcelTable";
string r = "";
SqlCommand cmd1 = new SqlCommand(s, con);
try
{
SqlDataAdapter da1 = new SqlDataAdapter(cmd1);
da1.Fill(dt1);
}
catch { }
int RecordCount;
RecordCount = Convert.ToInt32(cmd1.ExecuteScalar());
r = RecordCount.ToString();
Label1.Text = r;
con.Close();
int prv = Convert.ToInt32(r);
// Bulk Copy to SQL Server
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(sqlConnectionString))
{
bulkCopy.DestinationTableName = "ExcelTable";
bulkCopy.WriteToServer(dr);
con.Open();
SqlBulkCopyColumnMapping mapping1 = new SqlBulkCopyColumnMapping("id", "ida");
SqlBulkCopyColumnMapping mapping2 = new SqlBulkCopyColumnMapping("data", "dataa");
con.Close();
}
con.Open();
DataTable dt = new DataTable();
s = "select count(*) from ExcelTable"; r = "";
SqlCommand cmd = new SqlCommand(s, con);
try { SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
}
catch { }
RecordCount = Convert.ToInt32(cmd.ExecuteScalar());
r = RecordCount.ToString(); Label1.Text = r;
con.Close();
int ltr = Convert.ToInt32(r);
if (prv == ltr)
{
Label1.Text = "No records Added";
}
else
{
Label1.Text = "Records Added Successfully !";
}
}
}
Error:
No value given for one or more required parameters.
You created but didn't add the mappings to SqlBulkCopy.
Add the code below:
bulkCopy.ColumnMappings.Add(mapping1);
bulkCopy.ColumnMappings.Add(mapping2);

how to import multiple excel sheets into 2 sql server tables?

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");
}

Categories