简体   繁体   中英

Get Tables (workparts) of a sheet of excel by OpenXML SDK

I have 3 tables in a sheet of excel file, and I use OpenXML SDK to read the Excel file, like this:

SpreadSheetDocument document = SpreadSheetDDocument.open(/*read it*/);
foreach(Sheet sheet in document.WorkbookPart.Workbook.Sheets)
{
   //I need each table or work part of sheet here
}

So as you see I can get each sheet of Excel, but how can I get workparts in each sheet, like my 3 tables I should can iterate on these tables, does any one know about this? any suggestion?

Does this help?

// true for editable
using (SpreadsheetDocument xl = SpreadsheetDocument.Open("yourfile.xlsx", true))
{
    foreach (WorksheetPart wsp in xl.WorkbookPart.WorksheetParts)
    {
        foreach (TableDefinitionPart tdp in wsp.TableDefinitionParts)
        {
            // for example
            // tdp.Table.AutoFilter = new AutoFilter() { Reference = "B2:D3" };
        }
    }
}

Note that the actual cell data is not in the Table object, but in SheetData (under Worksheet of the WorksheetPart). Just so you know.

You can get the specific table from excel. Adding more to the answer of @Vincent

using (SpreadsheetDocument document= SpreadsheetDocument.Open("yourfile.xlsx", true))
{
    var workbookPart = document.WorkbookPart;
    var relationsShipId = workbookPart.Workbook.Descendants<Sheet>()
                    .FirstOrDefault(s => s.Name.Value.Trim().ToUpper() == "your sheetName")?.Id;

    var worksheetPart = (WorksheetPart)workbookPart.GetPartById(relationsShipId);

    TableDefinitionPart tableDefinitionPart = worksheetPart.TableDefinitionParts
                                                                       .FirstOrDefault(r =>
                                                                         r.Table.Name.Value.ToUpper() =="your Table Name");

    QueryTablePart queryTablePart = tableDefinitionPart.QueryTableParts.FirstOrDefault();

    Table excelTable = tableDefinitionPart.Table;

    var newCellRange = excelTable.Reference;
    var startCell = newCellRange.Value.Split(':')[0]; // you can have your own logic to find out row and column with this values
    var endCell = newCellRange.Value.Split(':')[1];// Then you can use them to extract values using regular open xml 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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