The problem : My code for Importing data into database from excel sheet works fine for .xls, but for .xlsx it gives "External table is not in the expected format." error.
Please help me with this.
The connection strings ive used are :
<add name="Excel03ConString" connectionString="Provider=Microsoft.Jet.OLEDB.4.0; Data Source={0};Extended Properties='Excel 8.0;HDR={1}'"/>
<add name="Excel07ConString" connectionString="Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 12.0;HDR={1}; IMEX=YES'"/>
The code is :
protected void Button2_Click(object sender, EventArgs e)
{
FileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
Extension = Path.GetExtension(FileUpload1.PostedFile.FileName);
FolderPath = ConfigurationManager.AppSettings["FolderPath"];
FilePath = FileUpload1.PostedFile.FileName;
Date = Calendar1.SelectedDate.ToShortDateString();
ImportData();
}
void ImportData()
{
string conStr = "";
switch (Extension)
{
case ".xls": //Excel 97-03
conStr = ConfigurationManager.ConnectionStrings["Excel03ConString"]
.ConnectionString;
break;
case ".xlsx": //Excel 07
conStr = ConfigurationManager.ConnectionStrings["Excel07ConString"]
.ConnectionString;
break;
}
try
{
conStr = String.Format(conStr, FilePath, "YES");
OleDbConnection Econ = new OleDbConnection(conStr);
Econ.Open();
//string Query = string.Format("Select [Id],[Name],[Status] FROM [{0}]", FileName);
//string Query = string.Format("Select [Id],[Name],[Status] FROM [XYZ$]");
string Query1 = string.Format("Select [Id],[Name],[Status] FROM [Sheet1$]");
OleDbCommand Ecom = new OleDbCommand(Query1, Econ);
DataSet ds = new DataSet();
OleDbDataAdapter oda = new OleDbDataAdapter(Ecom);
oda.Fill(ds);
string sqlconn = ConfigurationManager.ConnectionStrings["TempDatabaseConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(sqlconn);
con.Open();
DataTable Exceldt = ds.Tables[0];
//creating object of SqlBulkCopy
SqlBulkCopy objbulk = new SqlBulkCopy(con);
//assigning Destination table name
objbulk.DestinationTableName = "Trial";
//Mapping Table column
objbulk.ColumnMappings.Add("Id", "Id");
objbulk.ColumnMappings.Add("Name", "Name");
objbulk.ColumnMappings.Add("Status", "Status");
//inserting Datatable Records to DataBase
//con.Open();
objbulk.WriteToServer(Exceldt);
con.Close();
ds.Clear();
Econ.Close();
Ecom.Parameters.Clear();
objbulk.Close();
}
catch (Exception ex)
{
Response.Write(ex.ToString());
}
}