0

需要帮助以获取读取 XML 的简单方法。以下是我已采取的步骤:

  1. 添加了来自 Microsoft Excel 12.0 对象库 COM 的参考。
  2. 完全从另一个来源复制代码 http://csharp.net-informations.com/excel/csharp-read-excel.htm
  3. 我要求这是一种方法而不是 onclick 事件的唯一区别。
  4. 我得到的错误是 Error 10 An object reference is required for the non-static field, method, or property on codereleaseObject(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();
        }
    } 

}

}

4

2 回答 2

0

因为你的功能:

public static void executeRead()

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

于 2013-07-05T04:47:13.837 回答
0

releaseObject做为static方法_

private static void releaseObject(object obj)
于 2013-07-05T04:50:04.770 回答