简体   繁体   中英

Using Open XML to read an Excel spreadsheet, how do I determine the sheet that a Table is on?

If I have a loaded SpreadsheetDocument instance:

SpreadsheetDocument spreadsheetDocument

and iterate over the WorksheetParts:

foreach (var wp in spreadsheetDocument.WorkbookPart.WorksheetParts)

for every part that is a "Table" I can get to the table definition with:

wp.TableDefinitionParts

and grab the first entry. At this point I can grab the table name:

var tableName = tableDefinitionPart.Table.Name;

But how do I determine which sheet this this table is located in?

Given a WorksheetPart (as assigned to wp in your code), the first entry Parts list will be an Packaging.IdPartPair object:

var parts = wp.Parts.ToList();
var idPartPair = parts[0];

If you take a look at the value of

idPartPair.OpenXmlPart.Uri.OriginalString

it will be a string that looks like this:

/xl/tables/table2.xml

The only thing you care about is the number 2 in that string. Believe it or not, that's actually saying that the table is in the third sheet of the workbook (zero-based)

At this point, write your favorite code to extract the 2 out of the above code. My version is this, but I'm sure someone else can make this shorter:

var sheetNo = int.Parse(string.Concat(Path.GetFileNameWithoutExtension(idPartPair.OpenXmlPart.Uri.OriginalString).Skip(5)));

Next, get the list of sheets:

var sheets = spreadsheetDocument.WorkbookPart.Workbook.Sheets.ToList();

Then use sheetNo to index into it:

var sheet = (Sheet)sheets[sheetNo];

Then you can easily get the sheet name:

var sheetName = sheet.Name;

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