我已经编写了一个处理打开、写入和关闭Excel文件的类。
Excel类中的方法正由另一个调用调用。当我第一次调用addDatatoExcel
方法时,一切都正常,但是当我再次调用它时,我得到一个"System.NullReferenceException: Excel C#“。VB说我正在传递一个空对象。我知道错误是什么,我只是想不出如何防止它。
public class ExcelFile
{
public static ExcelFile C1;
private string excelFilePath = "C:\\Final.xlsx";
private int rowNumber = 1; // define first row number to enter data in Excel
Excel.Application excelApp;
Excel.Workbook excelWorkbook;
Excel.Worksheet excelWorksheet;
int ExcelCounter = 0;
int checker = 0;
string str4 = "h";
public void openExcel()
{
excelApp = null;
excelApp = new Excel.Application(); // create Excel App
excelWorkbook = excelApp.Workbooks.Add();
excelWorksheet = (Excel.Worksheet)excelWorkbook.Sheets.Add();
}
public void addDataToExcel(string str4)
{
excelWorksheet.Cells[5, 1] = str4;
ExcelCounter++;
}
public void closeExcel()
{
excelWorkbook.Close();
excelApp.Quit();
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(excelWorksheet);
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(excelWorkbook);
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(excelApp);
GC.Collect();
GC.WaitForPendingFinalizers();
}
}
我希望能够将数据添加到创建的第一个Excel工作表中。
这是调用Excel类中的函数的方法。
public void AddTextToLabel(string str)
{
ExcelFile _Excel = new ExcelFile();
if (flag == 1) // Celsius
{
//list Adding Function 1;
temp = Double.Parse(str);
x++;
list.Add(x, temp);
zedGraphControl1.Invalidate();
CreateChart(zedGraphControl1);
//Example();
if (Excelcounter == 0)
{
_Excel.openExcel();
Excelcounter++;
}
_Excel.addDataToExcel(str);
if (Excelcounter == 15)
{
_Excel.closeExcel();
}
}
}
我已经检查过了,传递给addDatatoExcel
的变量str
不是空的。还有其他参数在第二次调用函数时更改为null。这是因为我没有在每次调用AddDatatoExecl();
之间保存Excel文件吗?
第一次调用函数
第二次调用函数
我是C#的新手,所以请具体一点。谢谢
发布于 2020-11-28 07:09:18
您只在第一次打开Excel:
// Each time, you call this:
ExcelFile _Excel = new ExcelFile();
...
//The first time, this is called
if (Excelcounter == 0)
{
_Excel.openExcel();
Excelcounter++;
}
下一次调用AddTextToLabel
函数时
// A new instance is created
ExcelFile _Excel = new ExcelFile();
// The excel counter is not 0 so the _Excel.openExcel() will not be called.
if (Excelcounter == 0)
将您的代码更改为:
// Now your excel file is an instance member
// as is your Excelcounter
ExcelFile _Excel = new ExcelFile();
public void AddTextToLabel(string str)
{
if (flag == 1) // Celcuis
{
//list Adding Function 1;
temp = Double.Parse(str);
x++;
list.Add(x, temp);
zedGraphControl1.Invalidate();
CreateChart(zedGraphControl1);
//Example();
if (Excelcounter == 0)
{
_Excel.openExcel();
Excelcounter++;
}
_Excel.addDataToExcel(str);
if (Excelcounter == 15)
{
_Excel.closeExcel();
}
}
https://stackoverflow.com/questions/65047249
复制相似问题