2010-04-12 14 views
14

Ho bisogno di leggere i dati da un singolo foglio di lavoro in una cartella di lavoro Excel 2007 utilizzando Open XML SDK 2.0. Ho trascorso molto tempo alla ricerca di linee guida di base per farlo, ma ho trovato solo aiuto nella creazione di fogli di calcolo.Come faccio a leggere i dati da un foglio di calcolo utilizzando l'SDK formato OpenXML?

Come faccio a ripetere le righe in un foglio di lavoro e quindi a ripetere le celle in ogni riga, utilizzando questo SDK?

+0

@Otaku, non ho avuto la possibilità di indagare, ma una rapida occhiata ai link che hai suggerito suggerisce che saranno abbastanza preziosi e molto probabilmente risponderanno alla mia domanda. Grazie. – ProfK

+0

Hai avuto la possibilità di indagare su questo ancora? Fammi sapere se posso essere di ulteriore aiuto. –

+0

Sì, @Otaku, grazie. L'articolo "Using LINQ" è stato molto utile, anche se non sto facendo nulla, eccetto iterare righe e celle, ma mostra solo come accedere a un foglio. – ProfK

risposta

11

Il modo in cui lo faccio è con Linq. Ci sono molti esempi su questo argomento dall'uso dell'SDK per andare semplicemente con Open XML puro (senza SDK). Date un'occhiata a:

+0

Hey Todd, puoi aiutarmi. Ho riscontrato un problema con quanto segue: http://stackoverflow.com/questions/15791732/openxml-sdk-having-borders-for-cell Grazie in anticipo - Nate –

+0

@NatePet, mi dispiace per questo, non sono tutto che abbia familiarità con Excel, quindi probabilmente mi ci vorrà troppo tempo per dare una risposta a te. –

27

L'altra risposta sembrava più un meta-risposta. Sono stato alle prese con questo dato che usare LINQ funziona con parti di documento separate. Il codice seguente include una funzione wrapper per ottenere il valore da una cella, risolvendo eventuali possibili ricerche di stringhe.

public void ExcelDocTest() 
{ 
    Debug.WriteLine("Running through sheet."); 
    int rowsComplete = 0; 

    using (SpreadsheetDocument spreadsheetDocument = 
        SpreadsheetDocument.Open(@"path\to\Spreadsheet.xlsx", false)) 
    { 
     WorkbookPart workBookPart = spreadsheetDocument.WorkbookPart; 

     foreach (Sheet s in workBookPart.Workbook.Descendants<Sheet>()) 
     { 
      WorksheetPart wsPart = workBookPart.GetPartById(s.Id) as WorksheetPart; 
      Debug.WriteLine("Worksheet {1}:{2} - id({0}) {3}", s.Id, s.SheetId, s.Name, 
       wsPart == null ? "NOT FOUND!" : "found."); 

      if (wsPart == null) 
      { 
       continue; 
      } 

      Row[] rows = wsPart.Worksheet.Descendants<Row>().ToArray(); 

      //assumes the first row contains column names 
      foreach (Row row in wsPart.Worksheet.Descendants<Row>()) 
      { 
       rowsComplete++; 

       bool emptyRow = true; 
       List<object> rowData = new List<object>(); 
       string value; 

       foreach (Cell c in row.Elements<Cell>()) 
       { 
        value = GetCellValue(c); 
        emptyRow = emptyRow && string.IsNullOrWhiteSpace(value); 
        rowData.Add(value); 
       } 

       Debug.WriteLine("Row {0}: {1}", row, 
        emptyRow ? "EMPTY!" : string.Join(", ", rowData)); 
      } 
     } 

    } 
    Debug.WriteLine("Done, processed {0} rows.", rowsComplete); 
} 

public static string GetCellValue(Cell cell) 
{ 
    if (cell == null) 
     return null; 
    if (cell.DataType == null) 
     return cell.InnerText; 

    string value = cell.InnerText; 
    switch (cell.DataType.Value) 
    { 
     case CellValues.SharedString: 
      // For shared strings, look up the value in the shared strings table. 
      // Get worksheet from cell 
      OpenXmlElement parent = cell.Parent; 
      while (parent.Parent != null && parent.Parent != parent 
        && string.Compare(parent.LocalName, "worksheet", true) != 0) 
      { 
       parent = parent.Parent; 
      } 
      if (string.Compare(parent.LocalName, "worksheet", true) != 0) 
      { 
       throw new Exception("Unable to find parent worksheet."); 
      } 

      Worksheet ws = parent as Worksheet; 
      SpreadsheetDocument ssDoc = ws.WorksheetPart.OpenXmlPackage as SpreadsheetDocument; 
      SharedStringTablePart sstPart = ssDoc.WorkbookPart.GetPartsOfType<SharedStringTablePart>().FirstOrDefault(); 

      // lookup value in shared string table 
      if (sstPart != null && sstPart.SharedStringTable != null) 
      { 
       value = sstPart.SharedStringTable.ElementAt(int.Parse(value)).InnerText; 
      } 
      break; 

     //this case within a case is copied from msdn. 
     case CellValues.Boolean: 
      switch (value) 
      { 
       case "0": 
        value = "FALSE"; 
        break; 
       default: 
        value = "TRUE"; 
        break; 
      } 
      break; 
    } 
    return value; 
} 

Edit: Grazie @Nitin-Jadhav per la correzione a GetCellValue().

+0

Ciao, puoi aiutarmi. Ho problemi con http://stackoverflow.com/questions/15791732/openxml-sdk-having-borders-for-cell –

+0

Molto utile. Grazie. –

+0

Ottimo esempio, che funziona davvero, grazie! – berliner

Problemi correlati