zoukankan      html  css  js  c++  java
  • C# 读取Excel文件数据

    1、首先需要在管理NuGet程序包中添加外部包:ExcelDataReader,添加好后,不要忘记在命名空间那里引用。

    2、定义文件流,将文件流传入IExcelDataReader类型的对象excelReader中

     1  private DataSet ExcelGetDataTable(string excelPath)
     2         {
     3             FileStream stream = new FileStream(excelPath,FileMode.Open,FileAccess.Read);//定义文件流
     4             
     5             //首先判断传入的.xls文件还是xlsx文件
     6             int index = excelPath.LastIndexOf('.');//获取文件扩展名前‘.’的位置
     7             string extensionName = excelPath.Substring(index + 1);
     8             if(extensionName=="xls")
     9             {
    10                 //传入的xls文件---->97-2003format
    11                 excelReader = ExcelReaderFactory.CreateBinaryReader(stream);
    12             }
    13             if (extensionName == "xlsx")
    14             {
    15                 //传入的是xlsx文件---->2007 format
    16                 excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
    17             }
    18 
    19             //1、DataSet----the result of each spreadsheet will be created in the result Table
    20             DataSet result = excelReader.AsDataSet();
    21             return result;
    22             //2、DataSet----Create column names from first row
    23             //excelReader.IsFirstRowAsColumnNames = true;
    24             //DataSet result = excelReader.AsDataSet();
    25            //备注:excelReader是IExcelDataReader类型的对象,该类型在ExcelDataReader命名空间中定义。通过调用该对象的相关方法,获得DataSet对象。
    26 27 }

    3、DataSet对象----通过代码可以看出来如何获取DataSet对象的行和列的值

    DataSet dataList=this.ExcelGetDataTable(this.textBox2.Text);//接受读取的数据
    string arriveDataTime = dataList.Tables[0].Rows[3][40].ToString();
    //获取Excel文件的第一个表的第四行第41列的数据
  • 相关阅读:
    取消 Vue 中格式编译警告
    Vue 中提示报错 handlers[i].call is not a function解决方法
    PhpStorm 配置链接远程虚拟机
    Java 类提供了自定义的构造方法,那么类的默认构造不会被调用
    2019.9.30极限测试 04.JAVA语言课堂测试试卷-极限测试
    程序员修炼之道+从小工到专家 9月份读后感
    2019.9.23 作业2
    2019.9.23 作业1
    原码,补码,反码区分
    9.16日上课总结
  • 原文地址:https://www.cnblogs.com/WangYujie1994/p/11150387.html
Copyright © 2011-2022 走看看