Here The Simple Method Which Make DataSet From Excel Sheet
Public dataset dataSetFromExcel(string filePath)
{
string SheetName = GetExcelSheetNames( filePath );
string constring = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";Extended Properties='Excel 8.0;'";
OleDbConnection con = new OleDbConnection(constring);
string sql = "select * from [" + SheetName + "]";
OleDbDataAdapter da = new OleDbDataAdapter(sql, con);
da.TableMappings.Add("Table", SheetName);
try
{
da.Fill(ds);
if (ds.Tables.Count > 0)
{
ViewState["data"] = ds;
}
}
catch (Exception ex)
{
ex.ToString();
}
finally
{
if (con != null)
{
con.Close();
con.Dispose();
}
}
}
public static string GetExcelSheetNames(string excelFile)
{
OleDbConnection objConn = null;
DataTable dt = null;
try
{
String connString = "provider=Microsoft.Jet.OLEDB.4.0;Data Source='" + excelFile + "';Extended Properties=Excel 8.0;";
objConn = new OleDbConnection(connString);
objConn.Open();
dt = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if (dt == null)
{
return null;
}
string SheetName = "";
if (dt.Rows.Count > 0)
{
SheetName = dt.Rows[0]["TABLE_NAME"].ToString();
}
return SheetName;
}
catch (Exception ex)
{
ex.ToString();
return null;
}
finally
{
if (objConn != null)
{
objConn.Close();
objConn.Dispose();
}
if (dt != null)
{
dt.Dispose();
}
}
}
Public dataset dataSetFromExcel(string filePath)
{
string SheetName = GetExcelSheetNames( filePath );
string constring = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";Extended Properties='Excel 8.0;'";
OleDbConnection con = new OleDbConnection(constring);
string sql = "select * from [" + SheetName + "]";
OleDbDataAdapter da = new OleDbDataAdapter(sql, con);
da.TableMappings.Add("Table", SheetName);
try
{
da.Fill(ds);
if (ds.Tables.Count > 0)
{
ViewState["data"] = ds;
}
}
catch (Exception ex)
{
ex.ToString();
}
finally
{
if (con != null)
{
con.Close();
con.Dispose();
}
}
}
public static string GetExcelSheetNames(string excelFile)
{
OleDbConnection objConn = null;
DataTable dt = null;
try
{
String connString = "provider=Microsoft.Jet.OLEDB.4.0;Data Source='" + excelFile + "';Extended Properties=Excel 8.0;";
objConn = new OleDbConnection(connString);
objConn.Open();
dt = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if (dt == null)
{
return null;
}
string SheetName = "";
if (dt.Rows.Count > 0)
{
SheetName = dt.Rows[0]["TABLE_NAME"].ToString();
}
return SheetName;
}
catch (Exception ex)
{
ex.ToString();
return null;
}
finally
{
if (objConn != null)
{
objConn.Close();
objConn.Dispose();
}
if (dt != null)
{
dt.Dispose();
}
}
}
No comments:
Post a Comment