string strOledbConnection;
strOledbConnection = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + strExcelFilePath + "; Jet OLEDB:Engine Type=5;" + "Extended Properties=Excel 8.0;";
OleDbConnection conn = new OleDbConnection(strOledbConnection);
conn.Open();
DataTable dbSchema = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
string strsheetName = "Sheet1$";
if (dbSchema != null && dbSchema.Rows.Count > 0)
{
strsheetName = Convert.ToString(dbSchema.Rows[0]["TABLE_NAME"]);
}
conn.Close();
OleDbDataAdapter myCommand = new OleDbDataAdapter(" SELECT * FROM [" + strsheetName + "] ", strOledbConnection);
DataSet myDataSet = new DataSet(); myCommand.Fill(myDataSet);
Now you see, your old code would be 'SELECT * FROM [Sheet1$]' something, instead this will be dynamic. Make sure you put in your sheet name in the variable 'strExcelFilePath'
But in this case Convert.ToString(dbSchema.Rows[0]["TABLE_NAME"]) return first sheet name after sorting all sheet name with in excel file.how to get first sheet name??
ReplyDelete