2012-01-03 30 views
0

從Excel中讀取計算值我們試圖從其中包含加載公式的單元格中檢索計算值。 示例加載項「myUtilityl.xla」在Excel中正常工作。它檢索插件功能=ISOWEEKNUM(F9)的值。但是我們無法使用C#編程方式檢索該值。& Microsoft Object Library。加載項「myUtilityl.xla」連接到Excel。環境是VS2010使用AddIn公式和Microsoft Object Library

我在這裏提供示例代碼。

 string path = @"C:\Test.xls"; 
     Workbook theWorkbook; 
     Worksheet theWorksheet; 
     Range readRange; 
     Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();    
     theWorkbook = app.Workbooks.Open(path); 
     Sheets theSheets = (Sheets)theWorkbook.Worksheets; 
     theWorksheet = (Worksheet)theWorkbook.Worksheets.get_Item("Sheet1");    
     readRange = theWorksheet.get_Range("B1");    
     MessageBox.Show(Convert.ToString(readRange.Value)); 
     //theWorkbook.Save(); 
     app.Workbooks.Close(); 

我是微軟對象庫的新手。任何幫助或線索都會非常有幫助。

+0

你在消息框中得到什麼? – 2012-01-03 16:26:57

+0

獲取垃圾值--------------------------- ---------------- ----------- -2146826259 --------------------------- OK ----- ---------------------- – 2012-01-04 09:30:17

+0

是B1在myUtility.xla中調用UDF嗎? – 2012-01-04 09:34:43

回答

1

好Brijesh在現在的工作。唯一缺少的是我們必須打開xla。 app.Workbooks.Open(xlaFilePath); 然後它開始工作.. 非常感謝。我在這裏反正

 string path = @"C:\Test2.xls"; 
     string xlaPath = @"C:\Test2.xla"; 
     Workbook theWorkbook; 
     Worksheet theWorksheet, theWorksheet2; 
     Range readRange; 
     Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application(); 
     app.Workbooks.Open(xlaPath); 
     theWorkbook = app.Workbooks.Open(path); 
     theWorksheet2 = (Worksheet)theWorkbook.Worksheets.get_Item("Sheet2"); 
     theWorksheet2.get_Range("A3").Value = 7; 
     theWorksheet2.get_Range("A4").Value = 7; 
     theWorkbook.RefreshAll(); 

     theWorksheet = (Worksheet)theWorkbook.Worksheets.get_Item("Sheet1");   
     readRange = theWorksheet.get_Range("A1"); 
     Console.WriteLine(Convert.ToString(readRange.Value)); 
     Console.ReadLine();   //theWorkbook.Save();    
     theWorkbook.Close(); 
     app.Workbooks.Close(); 

發佈上面的代碼的代碼輸入的兩個值到Sheet 2中和VBA UDF計算值被檢索的細胞。

0

您可以添加以下代碼示例

 var addins = Application.AddIns.Add(xlaFilePath); 

     if (!addins.Installed) 
     { 
      addins.Installed = true;     
     } 
+0

當我嘗試使用以下代碼檢查已安裝的插件時,它顯示addin .. foreach(AddIn addin in app.AddIns) { MessageBox.Show(addin.FullName) ; } – 2012-01-04 12:26:47

+0

安裝屬性如何?這是真的嗎? – 2012-01-04 12:43:42

+0

安裝的屬性顯示「真」。那麼我的實際情況是這樣的。我有一個計算幾個UDF的Excel。我輸入特定工作表中的一個單元格,並讀取另一個工作表中調用UDF函數的單元格中的輸出。在上述情況下,單元格B1調用函數(「= ISONUMWEEK(F9)」)。單元格B1在Excel中顯示值,但不在代碼中。 – 2012-01-04 12:59:52

相關問題