Click here to Skip to main content
15,936,903 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Am having one excel file with 2 different worksheets as Sheet1 and Sheet2.Now I want to import these 2 different sheet values into 2 different sql tables(k2_Sheet1,k2_Sheet2).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:

using System.Data.SqlClient;
using System.Data.OleDb;

namespace ex2sl
{
public partial class _Default : System.Web.UI.Page
{

SqlConnection conn = new SqlConnection("Data Source=User-PC;Initial Catalog=master;Integrated Security=True");
DataSet ds;
DataTable Dt;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGrid();
}
}

private void ImporttoDatatable()
{
try
{
if (FlUploadcsv.HasFile)
{
string FileName = FlUploadcsv.FileName;
string path = string.Concat(Server.MapPath("~/Document/" + FlUploadcsv.FileName));
FlUploadcsv.PostedFile.SaveAs(path);
OleDbConnection OleDbcon = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=Excel 12.0;");
OleDbCommand cmd = new OleDbCommand("SELECT * FROM [Sheet1$]", OleDbcon);
OleDbDataAdapter objAdapter1 = new OleDbDataAdapter(cmd);
ds = new DataSet();
objAdapter1.Fill(ds);
Dt = ds.Tables[0];
}
}
catch (Exception ex)
{

}
}


private bool ValidateDate(string date)
{
try
{
string[] dateParts = date.Split('/');
DateTime testDate = new DateTime(Convert.ToInt32(dateParts[2]), Convert.ToInt32(dateParts[1]), Convert.ToInt32(dateParts[0]));
return true;
}
catch
{
return false;
}
}

private void InsertData()
{
for (int i = 0; i < Dt.Rows.Count; i++)
{
DataRow row = Dt.Rows[i];
int columnCount = Dt.Columns.Count;
string[] columns = new string[columnCount];
for (int j = 0; j < columnCount; j++)
{
columns[j] = row[j].ToString();
}
conn.Open();
string sql = "INSERT INTO EmpImport(EmployeeID,Name,Designation,DateOfBirth,City)";
sql += "VALUES('" + columns[0] + "','" + columns[1] + "','" + columns[2] + "',Convert(varchar(10),'" + columns[3] + "',103),'" + columns[4] + "')";
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.ExecuteNonQuery();
conn.Close();
}
}

protected void btnIpload_Click(object sender, EventArgs e)
{
ImporttoDatatable();
InsertData();
BindGrid();
}

private void BindGrid()
{
DataSet ds = new DataSet();
conn.Open();
string cmdstr = "Select * from EmpImport";
SqlDataAdapter adp = new SqlDataAdapter(cmdstr, conn);
adp.Fill(ds);
empdet.DataSource = ds;
empdet.DataBind();
ds.Dispose();
conn.Close();
}
}
}
Posted

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900