Hello,
I am using following code to export data from excel into SQL using ASP.NET.
protected void Upload(object sender, EventArgs e)
{
string excelPath = Server.MapPath("~/Files") + Path.GetFileName(FileUpload1.PostedFile.FileName);
FileUpload1.SaveAs(excelPath);
string conString = string.Empty;
string extension = Path.GetExtension(FileUpload1.PostedFile.FileName);
switch (extension)
{
case ".xls":
conString = ConfigurationManager.ConnectionStrings["Excel03ConString"].ConnectionString;
break;
case ".xlsx":
conString = ConfigurationManager.ConnectionStrings["Excel07+ConString"].ConnectionString;
break;
}
conString = string.Format(conString, excelPath);
using (OleDbConnection excel_con = new OleDbConnection(conString))
{
excel_con.Open();
string sheet1 = excel_con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null).Rows[0]["TABLE_NAME"].ToString();
DataTable dtExcelData = new DataTable();
dtExcelData.Columns.AddRange(new DataColumn[3]
{
new DataColumn("ID", typeof(string)),
new DataColumn("Name", typeof(DateTime)),
new DataColumn("Designation",typeof(DateTime))});
using (OleDbDataAdapter oda = new OleDbDataAdapter("SELECT * FROM [" + sheet1 + "]", excel_con))
{
oda.Fill(dtExcelData);
}
excel_con.Close();
string consString = ConfigurationManager.ConnectionStrings["TestConnection"].ConnectionString;
using (SqlConnection con = new SqlConnection(consString))
{
using (SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(con))
{
sqlBulkCopy.DestinationTableName = "dbo.Employee";
sqlBulkCopy.ColumnMappings.Add("ID", "ID");
sqlBulkCopy.ColumnMappings.Add("Name", "Name");
sqlBulkCopy.ColumnMappings.Add("Designation", "Designation");
con.Open();
sqlBulkCopy.WriteToServer(dtExcelData);
con.Close();
}
}
}
}
The problem is that in my Excel file the actual data is starting from Row 7.
So it is not working but whenever i move data to row 1 it fetches and uploades the data in SQL just fine.
So what i want is to predefine in my code that pick the data from row 7 in excel file.
Please help, as i am really stuck here.
UPDATE
Also just another query that my header name of SQL and Excel sheets are different, so unless both headers are same it does not pick the data, so is there anyway that i can keep the header different and still fetch the data?
Thanks
What I have tried:
Not much help available on internet regarding this