In this article, I am going to show how to read Excel file using c#. To achieve that we are going to use
Excel Data Reader (http://exceldatareader.codeplex.com/) DLL.
To get Excel Data Reader DLL to your project use NuGet
Code:
public void BtnUploadClick(object sender, EventArgs e) { string filePath = string.Empty; uploadPath = Server.MapPath("~/Excel/"); if (FileUpload1.HasFile) { String fileExtension = System.IO.Path.GetExtension(FileUpload1.FileName).ToLower(); String validExt = sAllowedExt; if (validExt.IndexOf("," + fileExtension + ",") != -1) { if (FileUpload1.FileBytes.Length <= maxsize) { filePath = uploadPath + FileUpload1.FileName; FileUpload1.PostedFile.SaveAs(filePath); Response.Write("File uploaded successfully."); FileStream stream = File.Open(filePath, FileMode.Open, FileAccess.Read); IExcelDataReader excelReader; if (filePath.Contains(".xlsx")) { //2. Reading from a OpenXml Excel file (2007 format; *.xlsx) excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream); } //... else { //1. Reading from a binary Excel file ('97-2003 format; *.xls) excelReader = ExcelReaderFactory.CreateBinaryReader(stream); } //... //3. DataSet - The result of each spreadsheet will be created in the result.Tables //DataSet result = excelReader.AsDataSet(); //... //4. DataSet - Create column names from first row excelReader.IsFirstRowAsColumnNames = true; DataSet result = excelReader.AsDataSet(); //5. Data Reader methods //foreach (DataRow item in result.Tables[0].Rows) //{ // //item[1].ToString(); //} GridView1.DataSource = result; GridView1.DataBind(); } else { Response.Write("File size exceeded the permitted limit."); return; } } else { Response.Write("This file type is not accepted."); return; } } }
Thanks
Download
[wpdm_file id=4]