protected void btnUpload_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
string sPath = Server.MapPath("~/BulkFolder/" + FileUpload1.FileName);
FileUpload1.SaveAs(sPath);
ImporttoSQL(sPath);
}
}
private void ImporttoSQL(string sPath)
{
try
{
string sSourceConstr = string.Format(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=""Excel 12.0 Xml;HDR=YES;""", sPath);
string sDestConstr = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
OleDbConnection sSourceConnection = new OleDbConnection(sSourceConstr);
using (sSourceConnection)
{
string sql = string.Format("Select [Sno],[Subject],[Question],[op1],[op2],[op3],[op4],[Answer] FROM [{0}]", "Sheet1$");
OleDbCommand command = new OleDbCommand(sql, sSourceConnection);
sSourceConnection.Open();
using (OleDbDataReader dr = command.ExecuteReader())
{
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(sDestConstr))
{
bulkCopy.DestinationTableName = "Questions";
bulkCopy.WriteToServer(dr);
Label1.Visible = true;
}
}
}
}
catch (Exception y)
{
Label1.Visible = true;
Label2.Visible = true;
Label3.Visible = true;
Label1.Text = "Cannot upload the quetions. Please check that";
Label2.Text = "1. All the values are present. No column is missing.";
Label3.Text = "2. Answer is in the numeric value or file format is wrong.";
}
}
Html Code
Untitled Page
Output
{
if (FileUpload1.HasFile)
{
string sPath = Server.MapPath("~/BulkFolder/" + FileUpload1.FileName);
FileUpload1.SaveAs(sPath);
ImporttoSQL(sPath);
}
}
private void ImporttoSQL(string sPath)
{
try
{
string sSourceConstr = string.Format(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=""Excel 12.0 Xml;HDR=YES;""", sPath);
string sDestConstr = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
OleDbConnection sSourceConnection = new OleDbConnection(sSourceConstr);
using (sSourceConnection)
{
string sql = string.Format("Select [Sno],[Subject],[Question],[op1],[op2],[op3],[op4],[Answer] FROM [{0}]", "Sheet1$");
OleDbCommand command = new OleDbCommand(sql, sSourceConnection);
sSourceConnection.Open();
using (OleDbDataReader dr = command.ExecuteReader())
{
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(sDestConstr))
{
bulkCopy.DestinationTableName = "Questions";
bulkCopy.WriteToServer(dr);
Label1.Visible = true;
}
}
}
}
catch (Exception y)
{
Label1.Visible = true;
Label2.Visible = true;
Label3.Visible = true;
Label1.Text = "Cannot upload the quetions. Please check that";
Label2.Text = "1. All the values are present. No column is missing.";
Label3.Text = "2. Answer is in the numeric value or file format is wrong.";
}
}
Html Code
Output
No comments:
Post a Comment