【发布时间】:2018-11-12 09:52:22
【问题描述】:
这被认为是重复的帖子,因为确切的代码用于另一个问题(大约 5 年前。)。基本上,我收到错误 System.NullreferenceException: 'Object reference not set to an instance on an object '. 每次我关闭表单时,xlWorkBook.Close(true, misValue, misValue); 行(见图)。基于原来的问题:Inserting multiple textbox data into an Excel file,我找不到和我有同样问题的人。我使用的代码与链接相同:
`using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using Excel = Microsoft.Office.Interop.Excel;
using System.Windows.Forms;
namespace Vehicledettry
{
public partial class Form1 : Form
{
Microsoft.Office.Interop.Excel.Application xlexcel;
Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
xlexcel = new Excel.Application();
xlexcel.Visible = true;
// Open a File
xlWorkBook = xlexcel.Workbooks.Open(" C:\\vehicledet.xlsx", 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);
xlWorkSheet.Cells[1, 1] = "Plate Number";
xlWorkSheet.Cells[1, 2] = "Car Model";
xlWorkSheet.Cells[1, 3] = "Car Brand";
xlWorkSheet.Cells[1, 4] = "Mileage";
}
private void button2_Click(object sender, EventArgs e)
{
int _lastRow = xlWorkSheet.Cells[xlWorkSheet.Rows.Count, 1].End[Excel.XlDirection.xlUp].Row + 1;
xlWorkSheet.Cells[_lastRow, 1] = Plate Number.Text;
xlWorkSheet.Cells[_lastRow, 2] = Car Model.Text;
xlWorkSheet.Cells[_lastRow, 3] = Car Brand.Text;
xlWorkSheet.Cells[_lastRow, 4] = Mileage.Text;
}
private void button3_Click(object sender, EventArgs e)
{
xlWorkBook.Close(true, misValue, misValue);
xlexcel.Quit();
releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlexcel);
}
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();
}
}
}
我尝试在每个按钮事件单击后复制xlWorkBook = xlexcel.Workbooks.Open(" C:\\vehicledet.xlsx", 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);,但同样的错误不断发生。希望我能得到一些帮助。谢谢。
【问题讨论】:
-
这是很多不好的做法。不难得到这个异常,只需在单击 button1 之前单击 button3。
-
嗨,汉斯。当我单击按钮 3 时,将弹出错误并且无法按下其他按钮。无论如何,按钮 3 用于关闭程序,所以如果我先按下它,我的所有数据甚至都不会被保存(没有差异,因为我什至无法运行程序:()。我会继续尝试。
-
您可以使用 EPPlus 之类的库直接生成
xlsx文件,而不是使用 Excel 互操作。 The API is more or less the same 但您不必担心安装 Excel、关闭和正确处理 COM 对象。