简体   繁体   English

将excel文件(.xls或.xlsx)的内容输入到数据集中

[英]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 我有一个名为test.xls的excel文件,我想把excel表中的内容放到数据集中。我可能尝试了一个代码,但它抛出异常,这是我的代码

 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();
 }

I'm going to assume you're using this http://exceldatareader.codeplex.com/ 我假设你正在使用这个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. “.xlsx”文件是压缩的xml文档。 "xls" are the older binary files. “xls”是较旧的二进制文件。 Also consider using System.IO.Path.GetExtension() to get the file extension since you'll notice Contains(".xls") is true for both file types. 还要考虑使用System.IO.Path.GetExtension()来获取文件扩展名,因为您会注意到两种文件类型的Contains(“。xls”)都为true。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM