获取工作薄中所有工作表名

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DocumentFormat.OpenXml.Packaging;//必须
using S = DocumentFormat.OpenXml.Spreadsheet.Sheets;//必须
using E = DocumentFormat.OpenXml.OpenXmlElement;//必须
using A = DocumentFormat.OpenXml.OpenXmlAttribute;//必须
//注:使用前要先在引用中添加这两个引用DocumentFormat.OpenXml , WindowsBase
namespace ClassLibrary1
{
public static class SheetName

{
    /// <summary>
    /// 提取工作薄中所有工作表的表名
    /// </summary>
    /// <param name="fileName">工作薄路径</param>
    /// <returns></returns>
    public static List<string> GetSheetInfo(string fileName)//参数为工作薄路径
    {
        // Open file as read-only.以只读方式打开文件
        using (SpreadsheetDocument mySpreadsheet = SpreadsheetDocument.Open(fileName, false))
        {
            List<string> list = new List<string>();
            int m = 0;
            S sheets = mySpreadsheet.WorkbookPart.Workbook.Sheets;
     
            // For each sheet, display the sheet information.显示工作表信息
            foreach (E sheet in sheets)
            {
                foreach (A attr in sheet.GetAttributes())
                {
                    if (m % 3 == 0)//因为attr.Value中包含工作表名,工作表序号和ID号
                    {
                        list.Add(attr.Value);//把工作表名装到List中
                    }
                    m++;
                }
            }
            return list;
        }
    }
}

}

posted @ 2019-12-25 07:20  zhujie-  阅读(493)  评论(0编辑  收藏  举报