[英]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 spreadsheetDocument
and iterate over the WorksheetParts: 并遍历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: 给定一个
WorksheetPart
(在代码中分配给wp
),第一个条目Parts
列表将是Packaging.IdPartPair
对象:
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. 您唯一关心的是该字符串中的数字
2
。 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. 此时,编写您喜欢的代码以从上面的代码中提取2。 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: 然后使用
sheetNo
进行索引:
var sheet = (Sheet)sheets[sheetNo];
Then you can easily get the sheet name: 然后,您可以轻松获得工作表名称:
var sheetName = sheet.Name;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.