打开一次Excel工作表并在其上迭代书写
本文关键字:书写 迭代 工作 Excel 一次 | 更新日期: 2023-09-27 17:56:52
我在 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
}
}
帮助将不胜感激,提前感谢!
我认为您希望具有以下代码:
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;
}
}
然后,您需要确保仅创建所需 Excel 工作表的a
实例。
你可以像这样使用它:
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;
}
}
我认为你想要的是将 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
}
}