如何使用OpenXML从Excel工作表中检索选项卡名称

时间:2011-09-21 17:50:00

标签: c# .net excel openxml openxml-sdk

我有一个电子表格文档,其中包含182列。我需要将电子表格数据放在数据表中,逐个标签,但我需要找出,因为我正在添加每个选项卡中的数据,选项卡名称是什么,并将选项卡名称添加到数据表中的列。

这就是我设置数据表的方法。

然后我循环工作簿并向下钻取到sheetData对象并遍历每一行和每列,获取单元格数据。

DataTable dt = new DataTable();
for (int i = 0; i <= col.GetUpperBound(0); i++)
{
    try
    {
        dt.Columns.Add(new DataColumn(col[i].ToString(), typeof(string)));
    }
    catch (Exception e)
    {
        MessageBox.Show("Uploader  Error" + e.ToString());
        return null;
    }
}

dt.Columns.Add(new DataColumn("SheetName", typeof(string)));

但是在我用于数据表的字符串数组的末尾,我需要添加选项卡名称。当我在Open XML中的表格中循环时,如何找到选项卡名称?

到目前为止,这是我的代码:

using (SpreadsheetDocument spreadSheetDocument = 
           SpreadsheetDocument.Open(Destination, false))
{
    WorkbookPart workbookPart = spreadSheetDocument.WorkbookPart;
    Workbook workbook = spreadSheetDocument.WorkbookPart.Workbook;

    Sheets sheets = 
        spreadSheetDocument
            .WorkbookPart
            .Workbook
            .GetFirstChild<DocumentFormat.OpenXml.Spreadsheet.Sheets>();

    OpenXmlElementList list = sheets.ChildElements;

    foreach (WorksheetPart worksheetpart in workbook.WorkbookPart.WorksheetParts)
    {
        Worksheet worksheet = worksheetpart.Worksheet;

        foreach (SheetData sheetData in worksheet.Elements<SheetData>())
        {
            foreach (Row row in sheetData.Elements())
            {
                string[] thisarr = new string[183];
                int index = 0;
                foreach (Cell cell in row.Elements())
                {
                    thisarr[(index)] = GetCellValue(spreadSheetDocument, cell);
                    index++;
                }
                thisarr[182] = ""; //need to add tabname here
                if (thisarr[0].ToString() != "")
                {
                    dt.Rows.Add(thisarr);
                }
            }
        }
    }
}

return dt;

请注意:我之前从

中的“list”的InnerXML属性中获取了选项卡名称
OpenXmlElementList list = sheets.ChildElements;

然而我注意到,当我在电子表格中循环时,它没有以正确的顺序获得选项卡名称。

4 个答案:

答案 0 :(得分:36)

这是一个方便的帮助方法,用于获取与WorksheetPart对应的Sheet:

public static Sheet GetSheetFromWorkSheet
    (WorkbookPart workbookPart, WorksheetPart worksheetPart)
{
    string relationshipId = workbookPart.GetIdOfPart(worksheetPart);
    IEnumerable<Sheet> sheets = workbookPart.Workbook.Sheets.Elements<Sheet>();
    return sheets.FirstOrDefault(s => s.Id.HasValue && s.Id.Value == relationshipId);
}

然后你可以从工作表Name-property:

获取名称
Sheet sheet = GetSheetFromWorkSheet(myWorkbookPart, myWorksheetPart);
string sheetName = sheet.Name;

...这将是&#34;标签名称&#34; OP提到了。

对于记录,相反的方法如下:

public static Worksheet GetWorkSheetFromSheet(WorkbookPart workbookPart, Sheet sheet)
{
    var worksheetPart = (WorksheetPart)workbookPart.GetPartById(sheet.Id);
    return worksheetPart.Worksheet;
}

...并且我们还可以添加以下方法:

public static IEnumerable<KeyValuePair<string, Worksheet>> GetNamedWorksheets
    (WorkbookPart workbookPart)
{
    return workbookPart.Workbook.Sheets.Elements<Sheet>()
        .Select(sheet => new KeyValuePair<string, Worksheet>
            (sheet.Name, GetWorkSheetFromSheet(workbookPart, sheet)));
}

现在,您可以轻松枚举所有工作表,包括其名称。

如果您愿意,请将其全部放入字典中进行基于名称的查找:

IDictionary<string, WorkSheet> wsDict = GetNamedWorksheets(myWorkbookPart)
    .ToDictionary(kvp => kvp.Key, kvp => kvp.Value);

...或者如果你只想要一个特定的名单:

public static Sheet GetSheetFromName(WorkbookPart workbookPart, string sheetName)
{
    return workbookPart.Workbook.Sheets.Elements<Sheet>()
        .FirstOrDefault(s => s.Name.HasValue && s.Name.Value == sheetName);
}

(然后调用GetWorkSheetFromSheet以获取相应的工作表。)

答案 1 :(得分:19)

工作表名称存储在WorkbookPart Sheets元素中,该元素具有元素Sheet的子元素,对应于Excel文件中的每个工作表。您所要做的就是从Sheets元素中获取正确的索引,这将是您循环中的Sheet。我在下面添加了一段代码来做你想做的事。

int sheetIndex = 0;
foreach (WorksheetPart worksheetpart in workbook.WorkbookPart.WorksheetParts)
{                     
    Worksheet worksheet = worksheetpart.Worksheet;

    // Grab the sheet name each time through your loop
    string sheetName = workbookPart.Workbook.Descendants<Sheet>().ElementAt(sheetIndex).Name;

    foreach (SheetData sheetData in worksheet.Elements<SheetData>())
    {

       ...
    }
    sheetIndex++;
}

答案 2 :(得分:6)

    Using spreadsheetDocument As SpreadsheetDocument = spreadsheetDocument.Open("D:\Libro1.xlsx", True)

        Dim workbookPart As WorkbookPart = spreadsheetDocument.WorkbookPart

        workbookPart.Workbook.Descendants(Of Sheet)()



        Dim worksheetPart As WorksheetPart = workbookPart.WorksheetParts.Last
        Dim text As String



        For Each Sheet As Sheet In spreadsheetDocument.WorkbookPart.Workbook.Sheets
            Dim sName As String = Sheet.Name
            Dim sID As String = Sheet.Id

            Dim part As WorksheetPart = workbookPart.GetPartById(sID)
            Dim actualSheet As Worksheet = part.Worksheet

            Dim sheetData As SheetData = part.Worksheet.Elements(Of SheetData)().First

            For Each r As Row In sheetData.Elements(Of Row)()
                For Each c As Cell In r.Elements(Of Cell)()
                    text = c.CellValue.Text
                    Console.Write(text & " ")
                Next
            Next
        Next

    End Using

    Console.Read()

答案 3 :(得分:0)

worksheet.GetAttribute("name","").Value