Dears,
I want to Upload an Excel file using browse option as Dataset, so I can get its return Value.
I am looking to import Excel file (with browse option) as a dataset to get (out Dataset) as a return value.
I have a code to import fixed excel file (no browse.) as a Dataset.
private static OleDbConnection GetDataFromExcel(out DataSet dataSet)
{
OleDbConnection oleDbConnection;
//Since I am using excel 2007, I have to specify the OLEDB connector for 2007
OleDbDataAdapter oleDbDataAdapter;
oleDbConnection =
new OleDbConnection(
@"provider=Microsoft.ACE.OLEDB.12.0;Data Source='d:\test_excel.xlsx';Extended Properties=Excel 12.0;");
oleDbDataAdapter = new OleDbDataAdapter("select rtrim(ltrim(name)) as [Name],rtrim(ltrim(password)) as [Password] from [Sheet1$]", oleDbConnection);
oleDbDataAdapter.TableMappings.Add("Table", "ExcelTable");
dataSet = new DataSet();
oleDbDataAdapter.Fill(dataSet);
return oleDbConnection;
}
And this code import excel file with browse option but not as a dataset.
protected void PopulateGrid(object sender, EventArgs e)
{
// CHECK IF A FILE HAS BEEN SELECTED.
if ((FileUpload.HasFile))
{
if (!Convert.IsDBNull(FileUpload.PostedFile) &
FileUpload.PostedFile.ContentLength > 0)
{
// SAVE THE SELECTED FILE IN THE ROOT DIRECTORY.
FileUpload.SaveAs(Server.MapPath(".") + "\\" + FileUpload.FileName);
// SET A CONNECTION WITH THE EXCEL FILE.
OleDbConnection myExcelConn = new OleDbConnection
("Provider=Microsoft.ACE.OLEDB.12.0; " +
"Data Source=" + Server.MapPath(".") + "\\" + FileUpload.FileName +
";Extended Properties=Excel 12.0;");
try
{
myExcelConn.Open();
// GET DATA FROM EXCEL SHEET.
OleDbCommand objOleDB = new OleDbCommand("SELECT *FROM [Sheet1$]", myExcelConn);
// READ THE DATA EXTRACTED FROM THE EXCEL FILE.
OleDbDataReader objBulkReader = null;
objBulkReader = objOleDB.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(objBulkReader);
// FINALLY, BIND THE EXTRACTED DATA TO THE GRIDVIEW.
GridView1.DataSource = dt;
GridView1.DataBind();
lblConfirm.Text = "DATA IMPORTED TO THE GRID, SUCCESSFULLY.";
lblConfirm.Attributes.Add("style", "color:green");
}
catch (Exception ex)
{
// SHOW ERROR MESSAGE, IF ANY.
lblConfirm.Text = ex.Message;
lblConfirm.Attributes.Add("style", "color:red");
}
finally
{
// CLEAR.
myExcelConn.Close(); myExcelConn = null;
}
}
}
}
Regards,