2013-07-05 24 views
0

獲取簡單的readxml方法需要幫助。 這裏是我所採取的步驟:獲取簡單的readxml方法需要幫助

  1. 添加引用從Microsoft Excel 12.0對象庫COM。
  2. 複製代碼完全從另一源 http://csharp.net-informations.com/excel/csharp-read-excel.htm
  3. 我會要求這是一個方法的唯一區別和Not onClick事件。
  4. 我得到的錯誤是錯誤10引用需要非靜態字段,方法或屬性的代碼releaseObject(xlWorkSheet); releaseObject(xlWorkBook); releaseObject(xlApp);

有什麼需要的步驟的對象?

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Windows.Forms; 
using Excel = Microsoft.Office.Interop.Excel; 

namespace projectName 
{ 
class frmReadXml 
{ 

    public static void executeRead() 
    { 

     Excel.Application xlApp = new Excel.Application(); 
     Excel.Workbook xlWorkBook; 
     Excel.Worksheet xlWorkSheet = new Excel.Worksheet(); 
     Excel.Range range; 

     string str; 
     int rCnt = 0; 
     int cCnt = 0; 



     xlWorkBook = xlApp.Workbooks.Open("csharp.net-informations.xls", 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0); 
     xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1); 

     range = xlWorkSheet.UsedRange; 

     for (rCnt = 1; rCnt <= range.Rows.Count; rCnt++) 
     { 
      for (cCnt = 1; cCnt <= range.Columns.Count; cCnt++) 
      { 
       str = (string)(range.Cells[rCnt, cCnt] as Excel.Range).Value2; 
       MessageBox.Show(str); 
      } 
     } 

     xlWorkBook.Close(true, null, null); 
     xlApp.Quit(); 

     releaseObject(xlWorkSheet); 
     releaseObject(xlWorkBook); 
     releaseObject(xlApp); 
    } 
    private void releaseObject(object obj) 
    { 
     try 
     { 
      System.Runtime.InteropServices.Marshal.ReleaseComObject(obj); 
      obj = null; 
     } 
     catch (Exception ex) 
     { 
      obj = null; 
      MessageBox.Show("Unable to release the Object " + ex.ToString()); 
     } 
     finally 
     { 
      GC.Collect(); 
     } 
    } 

} 

}

回答

0

使releaseObjectstatic方法

private static void releaseObject(object obj) 
+0

感謝您的幫助。非常感激 – user2552331

0

因爲你的函數:

public static void executeRead() 

被聲明爲static,它只有權訪問也被定義爲static等功能。刪除此功能上的static,或將其添加到其他功能。由於所有這些似乎都無法訪問frmReadExcel的任何班級成員,所以我建議您將它們全部設爲靜態。

+0

謝謝..我只是消除靜電,因爲我不知道它是什麼呢成倍。 – user2552331

+0

也許這篇文章將幫助你理解什麼'靜態'的意思:http://stackoverflow.com/questions/4124102/whats-a-static-method-in-c –

+0

啊原來,我會需要使用靜態爲此從另一個表單訪問。然後,我將靜態添加到其他方法。 – user2552331