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

时间:2021-11-13 13:27:22

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

1 个解决方案

#1


2  

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. "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.

这些测试是倒退的。 “.xlsx”文件是压缩的xml文档。 “xls”是较旧的二进制文件。还要考虑使用System.IO.Path.GetExtension()来获取文件扩展名,因为您会注意到两种文件类型的Contains(“。xls”)都为true。

#1


2  

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. "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.

这些测试是倒退的。 “.xlsx”文件是压缩的xml文档。 “xls”是较旧的二进制文件。还要考虑使用System.IO.Path.GetExtension()来获取文件扩展名,因为您会注意到两种文件类型的Contains(“。xls”)都为true。