asp.net reads the data in excel and binds it to gridview

  • 2020-12-07 04:00:31
  • OfStack

Foreground label, DropDownList, gridview controls

aspx. cs core code:
 
using System.Data.OleDb;// We need to introduce naming  
public void Excel_Click(object sender, EventArgs e) 
{ 
if (this.AttachmentFile.Value == "" && this.Label1.Text == "" && DropDownList2.SelectedValue == "") 
{ 
Response.Write("<script>window.alert(' Select the file to import ')</script>"); 
} 
if (this.AttachmentFile.Value != "" && this.DropDownList2.SelectedValue == "") 
{ 
HttpFileCollection files = HttpContext.Current.Request.Files; 
HttpPostedFile postedFile = files[0]; 
fileName = System.IO.Path.GetFileName(postedFile.FileName); 
if (fileName != "") 
{ 
postedFile.SaveAs("\\\\localhost\\ folder \\" + fileName); 
} 
string strConn; 
strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + "\\\\localhost\\ folder \\" + fileName + ";Extended Properties=Excel 8.0;";//this.AttachmentFile.Value.ToString() 
OleDbConnection conn = new OleDbConnection(strConn); 
conn.Open(); 
DataTable sheetNames = conn.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" }); 
foreach (DataRow dr in sheetNames.Rows) 
{ 
DropDownList2.Items.Add(dr[2].ToString()); 
} 
this.Label1.Text = "\\\\localhost\\ folder \\" + fileName;//this.AttachmentFile.Value.ToString(); 
conn.Close(); 
} 
if (this.Label1.Text.ToString() != "" && this.DropDownList2.SelectedValue != "")// && this.DropDownList1.SelectedValue.ToString() != " all " 
{ 

// Bound to the gridview 
GridView1.DataSource = createDataSource(DropDownList2.SelectedValue.ToString(), this.Label1.Text.ToString());//, this.DropDownList1.SelectedValue.ToString() 
GridView1.DataBind(); 


} 


} 
// In order to Excel Gets the data set for the data source  
private DataSet createDataSource(string select, string lable) 

{ 
string strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + lable + ";Extended Properties=Excel 8.0;"; 
string strsql = "select  The registration number , The name , The date of , Check-in time , Sign back time , department  from [" + select + "] order by  department , The date of , The name ";//excel Fields of a table  
OleDbConnection conn = new OleDbConnection(strCon); 
OleDbDataAdapter da = new OleDbDataAdapter(strsql, conn); 
try 
{ 
conn.Open(); 
DataSet ds = new DataSet(); 
da.Fill(ds); 
conn.Close(); 
return ds; 
} 
catch (Exception e) 
{ 
Response.Write("<script>window.alert(' There is no data , or " + e.Message + "')</script>"); 
return null; 
} 
} 

Above is the insertion of pre-07 version excel

Only minor changes will be required after version 07
 
string strCon = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + lable + ";Extended Properties=Excel 12.0;"; 

Related articles: