将excel文件(.xls或.xlsx)的内容放入Dataset

本文关键字:Dataset xlsx 文件 excel xls | 更新日期: 2023-09-27 18:04:34

我有一个名为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();
 }

将excel文件(.xls或.xlsx)的内容放入Dataset

我假设您正在使用这个http://exceldatareader.codeplex.com/

从你的代码:

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

这些测试是反向的。".xlsx"文件是压缩过的XML文档。"xls"是较旧的二进制文件。还可以考虑使用System.IO.Path.GetExtension()来获取文件扩展名,因为您会注意到Contains(".xls")对两种文件类型都为真。