博客
关于我
C#获取Excel中所有的Sheet名称
阅读量:432 次
发布时间: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/

    你可能感兴趣的文章
    Python中*args 和**kwargs的用法
    查看>>
    Python中*args 和**kwargs的用法
    查看>>
    Python中*args和**kwargs的使用
    查看>>
    python中0、1、True、False、if条件
    查看>>
    python中argparse模块关于 parse_args() 函数详解(全)
    查看>>
    python中base64编码与解码
    查看>>
    python中break怎么用_详解Python中break语句的用法
    查看>>
    python中del函数的垃圾回收
    查看>>
    Python中DrissionPage的详细解析与实战
    查看>>
    python中enumerate、变量类型转换
    查看>>
    python中execute是啥_python – 为什么“c.execute(…)”打破循环?
    查看>>
    python中exit和break区别_Python中exit()和sys.exit()之间的区别
    查看>>
    python中h5的用法
    查看>>
    python中http协议编程_HTTP编程
    查看>>
    python中import os_Python:相对导入与绝对导入(import)、os.path、__file__
    查看>>
    python中is和==操作符
    查看>>
    Python中range对象的使用以及打印九九乘法表
    查看>>
    Python中set.discard和set.remove方法之间的运行时差异?
    查看>>
    python中tkinter中value_输入字段中的python Tkinter get()值
    查看>>
    Python中wx.FlexGridSizer
    查看>>