博客
关于我
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报错unable to access ‘https://github.com/sohee-lee7/Squire.git/‘
    查看>>
    npm淘宝镜像过期npm ERR! request to https://registry.npm.taobao.org/vuex failed, reason: certificate has ex
    查看>>
    npm版本过高问题
    查看>>
    npm的“--force“和“--legacy-peer-deps“参数
    查看>>
    npm的安装和更新---npm工作笔记002
    查看>>
    npm的常用操作---npm工作笔记003
    查看>>
    npm的常用配置项---npm工作笔记004
    查看>>
    npm的问题:config global `--global`, `--local` are deprecated. Use `--location=global` instead 的解决办法
    查看>>
    npm编译报错You may need an additional loader to handle the result of these loaders
    查看>>
    npm设置淘宝镜像、升级等
    查看>>
    npm设置源地址,npm官方地址
    查看>>
    npm设置镜像如淘宝:http://npm.taobao.org/
    查看>>
    npm配置安装最新淘宝镜像,旧镜像会errror
    查看>>
    NPM酷库052:sax,按流解析XML
    查看>>
    npm错误 gyp错误 vs版本不对 msvs_version不兼容
    查看>>
    npm错误Error: Cannot find module ‘postcss-loader‘
    查看>>
    npm,yarn,cnpm 的区别
    查看>>
    NPOI
    查看>>
    NPOI之Excel——合并单元格、设置样式、输入公式
    查看>>
    NPOI初级教程
    查看>>