使用OpenXML以工作表名称读取Excel

时间:2018-04-22 12:25:03

标签: c# excel openxml openxml-sdk

我是OpenXML c#的新手,我想从excel文件中读取行。但我需要按名称阅读excel表。这是我读取第一张表的示例代码:

 using (var spreadSheet = SpreadsheetDocument.Open(path, true))
                {
                    WorkbookPart workbookPart = spreadSheet.WorkbookPart;
                    WorksheetPart worksheetPart = workbookPart.WorksheetParts.First();
                    SheetData sheetData = worksheetPart.Worksheet.Elements<SheetData>().First();

                    foreach (Row r in sheetData.Elements<Row>())
                    {
                        foreach (Cell c in r.Elements<Cell>())
                        {
                            if (c.DataType != null && c.DataType == CellValues.SharedString)
                            {
                               // reading cells
                            }
                        }
                    }

但是如何通过工作表名称和读取单元格找到。

1 个答案:

答案 0 :(得分:2)

我已经在下面的代码段中完成了它。它基本上是Workbook-&gt; Spreadsheet-&gt; Sheet然后获取工作表的Name属性。

基本底层xml看起来像这样:

<x:workbook>
 <x:sheets>
    <x:sheet name="Sheet1" sheetId="1" r:id="rId1" />
    <x:sheet name="TEST sheet Name" sheetId="2" r:id="rId2" />
  </x:sheets>
</x:workbook>

id值是Open XML包在内部用于标识每个工作表并将其与其他XML部分链接的值。这就是识别名称后的代码行使用GetPartById来获取WorksheetPart的原因。

using (SpreadsheetDocument doc = SpreadsheetDocument.Open(path, false))
{
    WorkbookPart bkPart = doc.WorkbookPart;
    DocumentFormat.OpenXml.Spreadsheet.Workbook workbook = bkPart.Workbook;
    DocumentFormat.OpenXml.Spreadsheet.Sheet s = workbook.Descendants<DocumentFormat.OpenXml.Spreadsheet.Sheet>().Where(sht => sht.Name == "Sheet1").FirstOrDefault();
    WorksheetPart wsPart = (WorksheetPart)bkPart.GetPartById(s.Id);
    DocumentFormat.OpenXml.Spreadsheet.SheetData sheetdata = wsPart.Worksheet.Elements<DocumentFormat.OpenXml.Spreadsheet.SheetData>().FirstOrDefault();

    foreach (DocumentFormat.OpenXml.Spreadsheet.Row r in sheetdata.Elements<DocumentFormat.OpenXml.Spreadsheet.Row>())
    {
        DocumentFormat.OpenXml.Spreadsheet.Cell c = r.Elements<DocumentFormat.OpenXml.Spreadsheet.Cell>().First();
        txt += c.CellValue.Text + Environment.NewLine;
    }
    this.txtMessages.Text += txt;
}