Opening of Excel sheet once and writing on it iteratively
my app in c# has a prob in writing to excel sheet. My app create excel sheet for its purpose and does not write in it. the below code is for reference only..
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
}
}
Help will be appreciated, thanks in advance!
I think you want to have code along the lines of the following:
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;
}
}
You then need to make sure, that you create only as many instances of a
as you want Excel sheets.
You can use it like this:
a aa = new a();
for(...)
aa.m();
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;
}
}
I think what you want is to declare oXL and oWB as member variables of class b. Try something like this:
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
}
}
精彩评论