需要有关获取readxml的简单方法的帮助

时间:2013-07-05 04:44:48

标签: c# xml visual-studio-2010

需要帮助才能获得readxml的简单方法。 以下是我采取的步骤:

  1. 从Microsoft Excel 12.0对象库COM添加了参考。
  2. 完全从其他来源复制代码 http://csharp.net-informations.com/excel/csharp-read-excel.htm
  3. 唯一的区别是我需要这个方法而不是 onclick事件。
  4. 我得到的错误是错误10代码releaseObject(xlWorkSheet); releaseObject(xlWorkBook); releaseObject(xlApp);上的非静态字段,方法或属性需要对象引用
  5. 需要哪些步骤?

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

    }

2 个答案:

答案 0 :(得分:0)

因为你的功能:

public static void executeRead()

声明为static,它只能访问也定义为static的其他函数。删除此功能上的static,或将其添加到其他功能。由于这些似乎都没有访问frmReadExcel的任何班级成员,我建议你将它们全部静态化。

答案 1 :(得分:0)

releaseObject设为static方法

private static void releaseObject(object obj)