Search code examples
c#excelc#-4.0openxmlopenxml-sdk

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?


Solution

  • 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.