2012-01-11 16 views
12

Ho un foglio di calcolo di Excel 2010 con 3 fogli di lavoro denominati Foglio1, Foglio2 e Foglio3.Apri SDK XML 2.0 per accedere al foglio di lavoro Excel 2010

Sto cercando di ottenere un riferimento a un foglio di lavoro per nome.

sto usando il codice:

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>(); 
} 

Sto cercando di ottenere un riferimento a Sheet2, ma non riesco a trovare un modo per farlo.

Mi sto avvicinando, ma non sono ancora arrivati:

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

Questo mi fa un riferimento al foglio, ma non per i dati sul foglio

Grazie

risposta

21

Quello che vuoi veramente è il WorksheetPart che è ciò che contiene lo SheetData che stai cercando. Afferrando lo Sheets sotto lo Workbook verranno forniti solo determinati metadati relativi ai fogli di lavoro. Ecco un esempio di come per afferrare che WorksheetPart (sentitevi liberi di aggiungere il controllo degli errori, come si vede in forma come Suppongo che il sheetName esiste già chiamando First e non 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); 
} 

Poi basta utilizzare il codice di cui sopra per afferrare il corretto riferimento a SheetData e sarai in grado di trovare i dati che desideri da lì.

+0

Grazie amurra !! –

3

Ecco un codice per elaborare un foglio di calcolo con un nome di scheda o foglio specifico e inviarlo a qualcosa di simile a CSV. (Ho scelto una pipe al posto della virgola).

Vorrei che fosse più semplice ottenere il valore da una cella, ma penso che questo sia ciò con cui siamo bloccati. Puoi vedere che faccio riferimento ai documenti MSDN dove ho ottenuto la maggior parte di questo codice. Questo è ciò che Microsoft consiglia.

/// <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; 
    } 
Problemi correlati