2012-01-11 79 views
12

我有一個Excel 2010電子表格,其中有3個名爲Sheet1,Sheet2和Sheet3的工作表。Open XML SDK 2.0可以按名稱訪問Excel 2010工作表

我試圖按名稱獲得對工作表的引用。

我正在使用的代碼:

using (SpreadsheetDocument myWorkbook = SpreadsheetDocument.Open(FileName, true)) 
{ 
    //Access the main Workbook part, which contains all references 
    WorkbookPart workbookPart = myWorkbook.WorkbookPart; 

    WorksheetPart worksheetPart = workbookPart.WorksheetParts.Last(); 

    // this gives me Sheet1 
    SheetData sheetData = worksheetPart.Worksheet.GetFirstChild<SheetData>(); 
} 

我試圖讓到Sheet2參考,但我不能找到一個方法來做到這一點。

我越來越近了,但我現在還沒有:

var x = workbookPart.Workbook.Sheets.Where(s=> s.GetAttribute("name", "").Value == "Sheet2").FirstOrDefault(); 

這讓我對錶的引用,而不是在紙張上的數據

感謝

回答

21

你真正想要的是WorksheetPart這是什麼包含SheetData你正在尋找。抓取Workbook下的Sheets只會爲您提供有關工作表的某些元數據。下面是關於如何抓住這WorksheetPart(隨意添加你認爲合適的錯誤檢查,因爲我承擔sheetName已經通過調用First而不是FirstOrDefault存在)爲例

public WorksheetPart GetWorksheetPart(WorkbookPart workbookPart, string sheetName) 
{ 
    string relId = workbookPart.Workbook.Descendants<Sheet>().First(s => sheetName.Equals(s.Name)).Id; 
    return (WorksheetPart)workbookPart.GetPartById(relId); 
} 

就用上面的代碼搶正確的SheetData參考,您將能夠從那裏找到您想要的數據。

+0

感謝amurra !! – 2012-01-11 15:10:50

3

下面是一些代碼,用於處理具有特定選項卡或工作表名稱的電子表格,並將其轉儲爲類似CSV的內容。 (我選擇了一個管道而不是逗號)。

我希望從細胞中獲得價值更容易,但我認爲這就是我們所堅持的。你可以看到我參考了MSDN文檔,其中我得到了大部分代碼。這是微軟推薦的。

/// <summary> 
    /// Got code from: https://msdn.microsoft.com/en-us/library/office/gg575571.aspx 
    /// </summary> 
    [Test] 
    public void WriteOutExcelFile() 
    { 
     var fileName = "ExcelFiles\\File_With_Many_Tabs.xlsx"; 
     var sheetName = "Submission Form"; // Existing tab name. 
     using (var document = SpreadsheetDocument.Open(fileName, isEditable: false)) 
     { 
      var workbookPart = document.WorkbookPart; 
      var sheet = workbookPart.Workbook.Descendants<Sheet>().FirstOrDefault(s => s.Name == sheetName); 
      var worksheetPart = (WorksheetPart)(workbookPart.GetPartById(sheet.Id)); 
      var sheetData = worksheetPart.Worksheet.Elements<SheetData>().First(); 

      foreach (var row in sheetData.Elements<Row>()) 
      { 
       foreach (var cell in row.Elements<Cell>()) 
       { 
        Console.Write("|" + GetCellValue(cell, workbookPart)); 
       } 
       Console.Write("\n"); 
      } 
     } 
    } 

    /// <summary> 
    /// Got code from: https://msdn.microsoft.com/en-us/library/office/hh298534.aspx 
    /// </summary> 
    /// <param name="cell"></param> 
    /// <param name="workbookPart"></param> 
    /// <returns></returns> 
    private string GetCellValue(Cell cell, WorkbookPart workbookPart) 
    { 
     if (cell == null) 
     { 
      return null; 
     } 

     var value = cell.CellFormula != null 
      ? cell.CellValue.InnerText 
      : cell.InnerText.Trim(); 

     // If the cell represents an integer number, you are done. 
     // For dates, this code returns the serialized value that 
     // represents the date. The code handles strings and 
     // Booleans individually. For shared strings, the code 
     // looks up the corresponding value in the shared string 
     // table. For Booleans, the code converts the value into 
     // the words TRUE or FALSE. 
     if (cell.DataType == null) 
     { 
      return value; 
     } 
     switch (cell.DataType.Value) 
     { 
      case CellValues.SharedString: 

       // For shared strings, look up the value in the 
       // shared strings table. 
       var stringTable = 
        workbookPart.GetPartsOfType<SharedStringTablePart>() 
         .FirstOrDefault(); 

       // If the shared string table is missing, something 
       // is wrong. Return the index that is in 
       // the cell. Otherwise, look up the correct text in 
       // the table. 
       if (stringTable != null) 
       { 
        value = 
         stringTable.SharedStringTable 
          .ElementAt(int.Parse(value)).InnerText; 
       } 
       break; 

      case CellValues.Boolean: 
       switch (value) 
       { 
        case "0": 
         value = "FALSE"; 
         break; 
        default: 
         value = "TRUE"; 
         break; 
       } 
       break; 
     } 
     return value; 
    }