简体   繁体   English

如何在Excel的Open XML SDK中按名称获取工作表

[英]How to get a Sheet by name in Open XML SDK for Excel

I am testing the possible replacement of the EPPlus library in an ASP.Net MVC application written in C# with the Open XML SDK library because of a bug in EPPlus we can't squash with Macro Enabled Spreadsheets. 我正在测试用Open XML SDK库用C#编写的用C#编写的ASP.Net MVC应用程序中是否可以替换EPPlus库,因为EPPlus中存在错误,因此我们无法使用启用宏的电子表格进行压缩。 One think I liked about EPPlus was that the I could use this: 我喜欢EPPlus的一个想法是我可以使用它:

public ExcelWorksheet this[string Name] { get; }

to get the worksheet by name. 按名称获取工作表。 Looking at the definition of the Sheets class in Open XML SDK, there is not a similar construct. 查看Open XML SDK中Sheets类的定义,没有类似的构造。

I already have the tab name. 我已经有了标签名称。 I need to get the associated worksheet so I can edit it without looping through all of the sheets each time I need the sheet. 我需要获取关联的工作表,这样我才能在每次需要工作表时都无需遍历所有工作表的情况下进行编辑。

Everything I found has been the opposite, getting the name of a Sheet object. 我发现的一切都是相反的,得到工作表对象的名称。 Is there a way to get the Sheet by the tab text in Open XML SDK? 是否可以通过Open XML SDK中的选项卡文本获取工作表? OR should I download the source and add this feature to the class? 还是应该下载源代码并将此功能添加到课程中?

This answer, however has what I was looking for - How to retrieve Tab names from excel sheet using OpenXML . 但是,这个答案正是我想要的- 如何使用OpenXML从excel表格中检索Tab名称 I'm working on implementing the changes into my application and will post the code then. 我正在努力将更改实施到我的应用程序中,然后将发布代码。 I wrapped the functionality into a generic utility class based upon that answer. 我根据该答案将功能包装到通用实用程序类中。

Utility Class Code: 实用程序类代码:

public static class OpenXMLUtilities
{
    public static void UpdateCell(SpreadsheetDocument spreadSheet, string sheetName, DataAccess.Domain.CellType cellType, string value, uint rowIndex, string columnName)
    {
        WorksheetPart worksheetPart = GetWorksheetPartByName(spreadSheet, sheetName);

        if (worksheetPart != null)
        {
            Cell cell = GetCell(worksheetPart.Worksheet, columnName, rowIndex);

            cell.CellValue = new CellValue(value);

            switch (cellType)
            {
                case DataAccess.Domain.CellType.BidLocation:
                case DataAccess.Domain.CellType.Constant:
                case DataAccess.Domain.CellType.Email:
                case DataAccess.Domain.CellType.General:
                case DataAccess.Domain.CellType.Industry:
                case DataAccess.Domain.CellType.Name:
                case DataAccess.Domain.CellType.ProposalNumber:
                case DataAccess.Domain.CellType.Department:
                case DataAccess.Domain.CellType.Money:
                case DataAccess.Domain.CellType.Phone:
                    cell.DataType = new EnumValue<CellValues>(CellValues.String);
                    break;
                case DataAccess.Domain.CellType.Date:
                    cell.DataType = new EnumValue<CellValues>(CellValues.Date);
                    break;
                case DataAccess.Domain.CellType.Float:
                case DataAccess.Domain.CellType.Integer:
                    cell.DataType = new EnumValue<CellValues>(CellValues.Number);
                    break;
                case DataAccess.Domain.CellType.YesNoOrBlank:
                case DataAccess.Domain.CellType.YesOrNo:
                    cell.DataType = new EnumValue<CellValues>(CellValues.Boolean);
                    break;
            }

            worksheetPart.Worksheet.Save();
        }
    }

    public static WorksheetPart GetWorksheetPartByName(SpreadsheetDocument document, string sheetName)
    {
        IEnumerable<Sheet> sheets = document.WorkbookPart.Workbook.GetFirstChild<Sheets>().Elements<Sheet>().Where(s => s.Name == sheetName);

        if (sheets.Count() == 0)
        {
            // The specified worksheet does not exist.
            return null;
        }

        string relationshipId = sheets.First().Id.Value;
        WorksheetPart worksheetPart = (WorksheetPart)document.WorkbookPart.GetPartById(relationshipId);

        return worksheetPart;
    }

    private static Cell GetCell(Worksheet worksheet, string columnName, uint rowIndex)
    {
        Row row = GetRow(worksheet, rowIndex);

        if (row == null)
        {
            return null;
        }

        return row.Elements<Cell>().Where(c => string.Compare(c.CellReference.Value, columnName + rowIndex, true) == 0).First();
    }
    private static Row GetRow(Worksheet worksheet, uint rowIndex)
    {
        return worksheet.GetFirstChild<SheetData>().Elements<Row>().Where(r => r.RowIndex == rowIndex).First();
    }

}

查找EPPlus源代码的URL https://github.com/JanKallman/EPPlus

You can use below method to get WorkSheet with sheetName. 您可以使用以下方法来获取带有sheetName的WorkSheet。

public static Worksheet GetworksheetBySheetName(string sheetName)
 {
   using (SpreadsheetDocument document = SpreadsheetDocument.Open(@"C:\Users\Public\Documents\Sheet7.xlsx", true))
   {
     var workbookPart = document.WorkbookPart;
                string relationshipId = workbookPart.Workbook.Descendants<Sheet>().FirstOrDefault(s => s.Name.Equals(sheetName))?.Id;

     var worksheet = ((WorksheetPart)workbookPart.GetPartById(relationshipId)).Worksheet;

     return worksheet;
   }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM