从 Open XML 包获取工作表信息
本主题演示如何使用 Open XML SDK for Office 中的类以编程方式从电子表格文档中的工作表检索信息。
spreadsheetML 文档的基本结构
SpreadsheetML 文档的基本文档结构由工作表和工作表元素组成,它们引用工作簿中的工作表。 将为每张工作表创建单独的 XML 文件。 例如,具有两个工作表 MySheet1 和 MySheet2 的工作簿的 SpreadsheetML 位于 Workbook.xml 文件中,并在以下代码示例中显示。
<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<workbook xmlns=https://schemas.openxmlformats.org/spreadsheetml/2006/main xmlns:r="https://schemas.openxmlformats.org/officeDocument/2006/relationships">
<sheets>
<sheet name="MySheet1" sheetId="1" r:id="rId1" />
<sheet name="MySheet2" sheetId="2" r:id="rId2" />
</sheets>
</workbook>
工作表 XML 文件包含一个或多个块级元素(如 sheetData )表示单元格表,并包含一个或多个 Row 元素。 row 包含一个或多个 Cell 元素。 每个单元格包含一个表示单元格的值的 CellValue 元素。 例如,工作簿中只在单元格 A1 中具有值 100 的第一张工作表的 SpreadsheetML 位于 Sheet1.xml 文件中,并且显示在以下代码示例中。
<?xml version="1.0" encoding="UTF-8" ?>
<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
<sheetData>
<row r="1">
<c r="A1">
<v>100</v>
</c>
</row>
</sheetData>
</worksheet>
使用 Open XML SDK,可以创建使用与 SpreadsheetML 元素对应的强类型类的文档结构和内容。 可以在 DocumentFormat.OpenXML.Spreadsheet 命名空间中找到这些类。 下表列出了与 workbook、 sheets、 sheet、 worksheet 和 sheetData 元素所对应类的类名称。
SpreadsheetML 元素 | Open XML SDK 类 | 说明 |
---|---|---|
工作簿 | DocumentFormat.OpenXML.Spreadsheet.Workbook | 主文档部件的根元素。 |
sheets | DocumentFormat.OpenXML.Spreadsheet.Sheets | 块级结构(如工作表、文件版本和 ISO/IEC 29500 规范中指定的其他项)的容器。 |
sheet | DocumentFormat.OpenXml.Spreadsheet.Sheet | 指向工作表定义文件的工作表。 |
worksheet | DocumentFormat.OpenXML.Spreadsheet。 Worksheet | 包含工作表数据的工作表定义文件。 |
sheetData | DocumentFormat.OpenXML.Spreadsheet.SheetData | 按行分组在一起的单元格表。 |
row | DocumentFormat.OpenXml.Spreadsheet.Row | 单元格表中的行。 |
c | DocumentFormat.OpenXml.Spreadsheet.Cell | 行中的单元格。 |
v | DocumentFormat.OpenXml.Spreadsheet.CellValue | 单元格的值。 |
示例代码的工作方式
打开文件进行只读访问后,实例化 Sheets 类。
Sheets? sheets = mySpreadsheet.WorkbookPart?.Workbook?.Sheets;
然后循环访问 Sheets 集合,并在每个元素中显示 OpenXmlElement 和 OpenXmlAttribute 。
foreach (OpenXmlElement sheet in sheets)
{
foreach (OpenXmlAttribute attr in sheet.GetAttributes())
{
Console.WriteLine("{0}: {1}", attr.LocalName, attr.Value);
}
}
通过显示属性信息,可获取电子表格文件中每个工作表的名称和 ID。
示例代码
以下是使用 C# 和 Visual Basic 编写的完整示例代码。
using DocumentFormat.OpenXml.Packaging;
using System;
using OpenXmlAttribute = DocumentFormat.OpenXml.OpenXmlAttribute;
using OpenXmlElement = DocumentFormat.OpenXml.OpenXmlElement;
using Sheets = DocumentFormat.OpenXml.Spreadsheet.Sheets;
static void GetSheetInfo(string fileName)
{
// Open file as read-only.
using (SpreadsheetDocument mySpreadsheet = SpreadsheetDocument.Open(fileName, false))
{
Sheets? sheets = mySpreadsheet.WorkbookPart?.Workbook?.Sheets;
if (sheets is not null)
{
// For each sheet, display the sheet information.
foreach (OpenXmlElement sheet in sheets)
{
foreach (OpenXmlAttribute attr in sheet.GetAttributes())
{
Console.WriteLine("{0}: {1}", attr.LocalName, attr.Value);
}
}
}
}
}