打开Excel工作表一次并反复写入

时间:2011-05-18 06:28:27

标签: c# excel automation

我在c#中的应用程序有一个写入excel表的问题。 我的应用程序为其目的创建excel表,但不写入。 以下代码仅供参考..

class a
{
    void m()
    {
        b bee=new b();    
        Excel.Application oXL;
        Excel._Workbook oWB;
        b.write(oXL,oWB); //will be called multiple times
    }
}

class b
{
    static b() //declared static so that only once excel workbook with sheets will be     created
    {
        Excel._Application oXL = new Excel.Application();
        Excel._Workbook oWB = (Excel._Workbook)(oXL.Workbooks.Add(Type.Missing));
    }

    write( Excel.Application oXL, Excel._Workbook oWB)
    {
        oXL.Visible = true; //Here its throwing, Object reference not set to an instance of an  
                    //Object
    }
}

提前感谢帮助,我们将不胜感激!

2 个答案:

答案 0 :(得分:0)

void m()
{
   b bee=new b();    
   Excel.Application oXL; // not initialized here!
   Excel._Workbook oWB;   // not initialized here!
   b.write(oXL,oWB);      // calling with uninitialized values! 
}

// ...

class b
{
   static b() 
   {

       // here you declare two local variables not visible outside of your 
       // static constructor.
       Excel._Application oXL = new Excel.Application();
       Excel._Workbook oWB = (Excel._Workbook)(oXL.Workbooks.Add(Type.Missing));
   }

   // oXL here is a parameter, meaning it is completely different from
   // the local oXL in your static constructor
   void write( Excel.Application oXL, Excel._Workbook oWB)
   {
        oXL.Visible = true; 
   }
 }

我认为你想要的是将oXL和oWB声明为b类的成员变量。尝试这样的事情:

void m()
{
   b bee=new b();    
   b.write();
}

// ...

public class b
{
   Excel._Application oXL;
   Excel._Workbook oWB;

   public b() 
   {

       oXL = new Excel.Application();
       oWB = (Excel._Workbook)(oXL.Workbooks.Add(Type.Missing));
   }

   public void write()
   {
        // do something with cXL and oWB here
   }
 }

答案 1 :(得分:0)

我认为您希望获得以下代码:

class a
{
    b bee;
    public a()
    {
        bee = new b();
    }

    void m()
    {
        b.write(oXL,oWB); //will be called multiple times
    }
}

class b
{
    public b()
    {
        Excel._Application oXL = new Excel.Application();
        Excel._Workbook oWB = (Excel._Workbook)(oXL.Workbooks.Add(Type.Missing));
    }

    write()
    {
        oXL.Visible = true;
    }
}

然后,您需要确保只创建a的实例,就像您想要Excel工作表一样。

你可以像这样使用它:

a aa = new a();
for(...)
    aa.m();