Reading excel file in asp.net
The followiing are that code that I have used to read excel file:
Use file selector to upload file:
DataSet myDataset = new DataSet();
if (!FullFileName.Equals("")){
OleDbConnection conn = new OleDbConnection();
OleDbCommand cmd = new OleDbCommand();
OleDbDataAdapter da = new OleDbDataAdapter();
string query = null;
string connString = "";
string strFileType = System.IO.Path.GetExtension(FullFileName).ToString().ToLower();
if (strFileType.Trim() == ".xls"){
connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + FullFileName + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";
}
else if (strFileType.Trim() == ".xlsx"){
connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + FullFileName + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
}
//Create the connection object
conn = new OleDbConnection(connString);
//Open connection
if (conn.State == ConnectionState.Closed) conn.Open();
foreach (DataRow row in conn.GetSchema("tables").Rows) {
string name = row["TABLE_NAME"].ToString();
if (name.Trim().Length==4) { //Only PNH$, REP$, KOS$ is allow
DataSet dSet = new DataSet();
OleDbDataAdapter dAdapter = new OleDbDataAdapter("SELECT * FROM [" + name + "]", conn);
dAdapter.Fill(dSet);
DataTable dTable = dSet.Tables[0].Copy();
dTable.TableName = name;
myDataset.Tables.Add(dTable);
dAdapter.Dispose();
dSet.Dispose();
}
}
conn.Close();
conn.Dispose();
}
return myDataset;
Use file selector to upload file:
- <div><table style="height: 70px; width: 404px;"><tbody>
- <tr> <td class="style1">Select Date :</td> <td class="style2"></td> </tr>
- <tr> <td class="style1">Upload Excel File :</td> <td class="style2">
- <asp:fileupload id="FileUpload1" runat="server"></asp:fileupload></td> </tr>
- </tbody></table></div><asp:button id="btnUpload" onclick="btnUpload_Click" runat="server" text="Upload Excel File">
- </asp:button>
- <asp:gridview id="ExcelGridView" runat="server">
- </asp:gridview>
And Action on button Upload Excel File :
protected void btnUpload_Click(object sender, EventArgs e) { if (FileUpload1.FileName.ToString() != "" && FileUpload1.ToString().Contains(".")) { String filepath = Server.MapPath("UploadedFiles"); FileUpload1.SaveAs(filepath + "\\" + FileUpload1.FileName.Split('\\')[FileUpload1.FileName.Split('\\').Length - 1]); string excelPath = (filepath + "\\" + FileUpload1.FileName.Split('\\')[FileUpload1.FileName.Split('\\').Length - 1]);
ExcelGridView.DataSource = GetExcelData(excelPath); ExcelGridView.DataBind(); } }
Full reference can be seen at stackoverflow or aspdotnetmetters
Comments
Post a Comment