First, add a namespace.
Copy codeThe Code is as follows:
Using System. Data. OleDb;
Protected void Page_Load (object sender, EventArgs e)
{
If (! IsPostBack)
{
Strfile = Request. QueryString ["filename"]; // path of the File Uploaded from other pages
Excel (strfile );
}
}
Private void Excel (string filepath)
{
Try
{
Dataset ds = new DataSet ();
String ConnStr = "Provider = Microsoft. Jet. OleDb.4.0; data source =" + filepath +
"; Extended Properties = 'excel 8.0; HDR = YES; IMEX = 1'"; // connect the Excel String
String query = "SELECT * FROM [student $]"; // table name in Excel
OleDbCommand oleCommand = new OleDbCommand (query, new OleDbConnection (ConnStr ));
OleDbDataAdapter oleAdapter = new OleDbDataAdapter (oleCommand );
OleAdapter. Fill (ds, "[student $]");
Rowcount = ds. Tables [0]. Rows. Count;
Gridview1.DataSource = ds;
Gridview1.DataBind ();
Lblmes. Text = "uploaded successfully. The data is as follows. Please confirm:"; // The lblmes is a label and a prompt is displayed.
}
Catch (OleDbException)
{
String filename = filepath. Substring (filepath. LastIndexOf ('/') + 1 );
Lblmes. Text = "error! Check whether the uploaded file is correct! The currently uploaded file is: "+ filename;
LbtnSure. Visible = false;
}
Catch (Exception ee)
{
Lblmes. Text = ee. Message;
}
}
Implementation Code for asp.net to read and display excel Data
Create dynamic Excel with C # In Asp.net
Implementation Code of asp.net excel operations