2013-10-24 2 views
0

Я хочу массив или список, содержащий все значения всех ячеек в электронной таблице. Существует определенное количество столбцов, но любое количество строк. Это метод, который я получил из msdn.com, и я хочу знать, могу ли я его изменить, чтобы вернуть все значения в электронную таблицу, или если есть способ получить все ячейки, у которых были значения, а затем создать построитель строк для повторения через каждый адрес. На самом деле, я пытаюсь разобраться в этом SDK и надеюсь, что вы, ребята, можете мне рассказать. Вот метод:Как изменить этот метод, чтобы вернуть строковый массив

public static string GetCellValue(string fileName, 
string sheetName, 
string addressName) 

{ строковое значение = NULL;

// Open the spreadsheet document for read-only access. 
using (SpreadsheetDocument document = 
    SpreadsheetDocument.Open(fileName, false)) 
{ 
    // Retrieve a reference to the workbook part. 
    WorkbookPart wbPart = document.WorkbookPart; 

    // Find the sheet with the supplied name, and then use that 
    // Sheet object to retrieve a reference to the first worksheet. 
    Sheet theSheet = wbPart.Workbook.Descendants<Sheet>(). 
     Where(s => s.Name == sheetName).FirstOrDefault(); 

    // Throw an exception if there is no sheet. 
    if (theSheet == null) 
    { 
     throw new ArgumentException("sheetName"); 
    } 

    // Retrieve a reference to the worksheet part. 
    WorksheetPart wsPart = 
     (WorksheetPart)(wbPart.GetPartById(theSheet.Id)); 

    // Use its Worksheet property to get a reference to the cell 
    // whose address matches the address you supplied. 
    Cell theCell = wsPart.Worksheet.Descendants<Cell>(). 
     Where(c => c.CellReference == addressName).FirstOrDefault(); 

    // If the cell does not exist, return an empty string. 
    if (theCell != null) 
    { 
     value = theCell.InnerText; 

     // 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 (theCell.DataType != null) 
     { 
      switch (theCell.DataType.Value) 
      { 
       case CellValues.SharedString: 

        // For shared strings, look up the value in the 
        // shared strings table. 
        var stringTable = 
         wbPart.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; 

}

Я очень признателен за любую помощь.

ответ

1

Следующий фрагмент кода захватывает все клетки и фильтрует его вниз только тот, который мы пытаемся найти ...

Cell theCell = wsPart.Worksheet.Descendants<Cell>(). 
    Where(c => c.CellReference == addressName).FirstOrDefault(); 

Если удалить Where(...), что должно дать вам все клетки ...

var cells = wsPart.Worksheet.Descendants<Cell>(); 

Теперь, когда у вас есть, что вы можете взять кусок кода внутри if (theCell != null) { ... } блока, сделать его метод, который принимает Cell (я назвал его ProcessCell здесь, он должен бы быть static функции, которая возвращает string), и называют его внутри foreach петли, как это:

var results = new List<String>(); 
foreach cell in cells 
{ 
    results.Add(ProcessCell(cell)); 
} 

, а затем просто вернуть свои результаты!

return results; 

Технически я не ответил на ваш вопрос, так как тип возврата является List<String> вместо массива, но я думаю, вы можете понять, что часть, если это действительно необходимо;)

Смежные вопросы