博客
关于我
C#获取Excel中所有的Sheet名称
阅读量:431 次
发布时间:2019-03-06

本文共 1400 字,大约阅读时间需要 4 分钟。

使用C#与Excel交互读取工作表名称

在C#中使用Excel.Application类可以方便地读取Excel文件中的工作表名称。本节将详细介绍如何实现这一功能。

一、基本操作步骤

  • 创建Excel应用程序实例
  • 首先,我们需要创建一个Excel.Application实例:

    Excel.Application myExcel = new Excel.Application();object missing = System.Reflection.Missing.Value;

    1. 打开Excel文件
    2. 接下来,使用myExcel打开指定的Excel文件:

      myExcel.Application.Workbooks.Open(this.txtFile.Text,missing,missing,missing,missing,missing,missing,missing,missing,missing,missing,missing,missing,missing,missing);

      请确保将this.txtFile.Text替换为实际的Excel文件路径。

      1. 获取工作表
      2. 打开文件后,获取第一个工作表:

        Excel.Workbook myBook = myExcel.Workbooks[1];Excel.Worksheet sheet = (Excel.Worksheet)myBook.Sheets[1];string sheetName = sheet.Name;

        二、获取所有工作表名称

        除了获取单个工作表名称外,我们还可以编写一个函数,获取Excel文件中所有工作表的名称。以下是一个实现代码示例:

        public static StringCollection ExcelSheetName(string filepath){StringCollection names = new StringCollection();string strConn = "Provider=Microsoft.Ace.OLEDB.12.0;Data Source=" + filepath + ";Extended Properties='Excel 12.0;HDR=Yes;IMEX=2'";OleDbConnection conn = new OleDbConnection(strConn);conn.Open();DataTable sheetNames = conn.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables,new object[] { null, null, null, "TABLE" });conn.Close();

        foreach (DataRow dr in sheetNames.Rows){    names.Add(dr[2].ToString());}return names;

        }

        三、注意事项

        在操作完成后,务必按照以下步骤关闭Excel资源:

      3. 关闭工作簿:
      4. myBook.Close(Type.Missing, Type.Missing, Type.Missing);

        1. 退出Excel应用程序:
        2. myExcel.Quit();

          以上代码示例为基础,具体使用时请根据实际需求进行调整。

    转载地址:http://bbfyz.baihongyu.com/

    你可能感兴趣的文章
    npm install digital envelope routines::unsupported解决方法
    查看>>
    npm install 卡着不动的解决方法
    查看>>
    npm install 报错 EEXIST File exists 的解决方法
    查看>>
    npm install 报错 ERR_SOCKET_TIMEOUT 的解决方法
    查看>>
    npm install 报错 Failed to connect to github.com port 443 的解决方法
    查看>>
    npm install 报错 fatal: unable to connect to github.com 的解决方法
    查看>>
    npm install 报错 no such file or directory 的解决方法
    查看>>
    npm install 权限问题
    查看>>
    npm install报错,证书验证失败unable to get local issuer certificate
    查看>>
    npm install无法生成node_modules的解决方法
    查看>>
    npm install的--save和--save-dev使用说明
    查看>>
    npm node pm2相关问题
    查看>>
    npm run build 失败Compiler server unexpectedly exited with code: null and signal: SIGBUS
    查看>>
    npm run build报Cannot find module错误的解决方法
    查看>>
    npm run build部署到云服务器中的Nginx(图文配置)
    查看>>
    npm run dev 和npm dev、npm run start和npm start、npm run serve和npm serve等的区别
    查看>>
    npm run dev 报错PS ‘vite‘ 不是内部或外部命令,也不是可运行的程序或批处理文件。
    查看>>
    npm scripts 使用指南
    查看>>
    npm should be run outside of the node repl, in your normal shell
    查看>>
    npm start运行了什么
    查看>>