Anilkumar
Anilkumar

Reputation: 85

Take contents of an excel file (.xls or .xlsx) in to Dataset

i have an excel file named test.xls and i want to get the contents in the excel sheet into a Dataset.Is it possible i tried a code but it throws exception,here is my code

 string FilePath = Server.MapPath("portals\\_default") + "\\" + upprice.FileName;
 upprice.PostedFile.SaveAs(FilePath);
 FileStream stream = File.Open(FilePath, FileMode.Open,    FileAccess.Read);
 if (upprice.FileName.Contains(".xlsx"))
 {
  IExcelDataReader excelReader = ExcelReaderFactory.CreateBinaryReader(stream);
   DataSet result = excelReader.AsDataSet();
 }

Upvotes: 0

Views: 2579

Answers (1)

enz0
enz0

Reputation: 131

I'm going to assume you're using this http://exceldatareader.codeplex.com/

From your code:

if (upprice.FileName.Contains(".xlsx"))
 {
  IExcelDataReader excelReader = ExcelReaderFactory.CreateBinaryReader(stream);
   DataSet result = excelReader.AsDataSet();
 }
 else if (upprice.FileName.Contains(".xls"))
 {
  IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
  DataSet result = excelReader.AsDataSet();
 } 

these tests are backwards. ".xlsx" files are zipped xml documents. "xls" are the older binary files. Also consider using System.IO.Path.GetExtension() to get the file extension since you'll notice Contains(".xls") is true for both file types.

Upvotes: 2

Related Questions