2012-06-12 25 views
0

我編寫了一個方法,用於在傳遞文件名,工作表名稱和單元格地址時返回Excel工作表單元格值。遞歸調用方法來獲取Excel工作表值。

public static string GetCellValue(string fileName, string sheetName, string addressName) 
     { 
      string value = null; 


      using (SpreadsheetDocument document = SpreadsheetDocument.Open(fileName, false)) 
      { 

       WorkbookPart wbPart = document.WorkbookPart; 


        Where(s => s.Name == sheetName).FirstOrDefault(); 


       if (theSheet == null) 
       { 
        throw new ArgumentException("sheetName"); 
       } 


       WorksheetPart wsPart = 
        (WorksheetPart)(wbPart.GetPartById(theSheet.Id)); 


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


       if (theCell != null) 
       { 
        value = theCell.InnerText; 


        if (theCell.DataType != null) 
        { 
         switch (theCell.DataType.Value) 
         { 
          case CellValues.SharedString: 
. 
           var stringTable = 
            wbPart.GetPartsOfType<SharedStringTablePart>() 
            .FirstOrDefault(); 

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

這裏是如何調用上面的方法。

private void button1_Click(object sender, EventArgs e) 
     { 
      const string fileName = @"C:\Users\dkumarage\Desktop\Book1.xlsx"; 
      string value = GetCellValue(fileName, "Sheet1", "A1"); 
      textBox1.Text = value; 
     } 

這樣我只能獲得1個單元格的值。我怎樣才能遞歸地調用這個方法來獲得所有的單元格值。請幫幫我。 (在這裏我可以不通過範圍。因爲我不知道的範圍內,而是我必須使用一段時間(沒有結束行))

謝謝

+1

從你的解釋我沒有看到使用遞歸的好處。另外''while'和哪裏有什麼錯誤使用它? –

+0

我只想從excel中獲取所有的值,而不是獲取一行。我不知道該怎麼做。 – devan

回答

1

我不知道你爲什麼想要它是遞歸的。無論如何,這裏是你想要做的非遞歸版本。它使用Excel interop,並且我沒有打算管理異常(比如文件未找到或者工作表不存在等等),但它應該給出一個起點。

public static List<string> GetCellValue(string fileName, string sheetName, string addressName) 
    { 
     List<string> result = new List<String>; 
     object hmissing = System.Reflection.Missing.Value; 
     Application app = new ApplicationClass(); 
     Workbook aWb = app.Workbooks.Open(fileName, hmissing, hmissing, hmissing, hmissing, 
      hmissing, hmissing, hmissing, hmissing, hmissing, hmissing, hmissing, hmissing, hmissing, 
      hmissing); 
     Worksheet aWs = aWb.Worksheets[sheetName] as Worksheet; 
     object[,] values = aWs.UsedRange.get_Value(hmissing) as object[,]; 
     foreach (object anObj in values) 
      if (anObj != null) 
       result.Add(anObj.ToString()); 
     aWb.Close(false, hmissing, hmissing); 
     app.Quit();   
     return result; 
    }