c#winforms VS2017与excel链接:关闭表单时出错
这被认为是一篇重复的文章,因为确切的代码用于另一个问题(大约5年前)。基本上,我得到了错误System.NullreferenceException:“对象引用未设置为对象上的实例”。对于第c#winforms VS2017与excel链接:关闭表单时出错,c#,excel,winforms,C#,Excel,Winforms,这被认为是一篇重复的文章,因为确切的代码用于另一个问题(大约5年前)。基本上,我得到了错误System.NullreferenceException:“对象引用未设置为对象上的实例”。对于第xl工作簿.Close行(true,misValue,misValue)每次我关闭表单时(见图)。根据原来的问题:,我找不到其他人有和我一样的问题。我使用的代码与链接相同: `using System; using System.Collections.Generic; using System.Comp
xl工作簿.Close行(true,misValue,misValue)代码>每次我关闭表单时(见图)。根据原来的问题:,我找不到其他人有和我一样的问题。我使用的代码与链接相同:
`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)每次单击按钮事件后,都会发生相同的错误。希望我能得到一些帮助。谢谢 (根据反馈进行编辑)见下文。文本框中的数据将自动进入所选的现有excel文件。这是对帮助的巨大赞扬
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Excel = Microsoft.Office.Interop.Excel;
using System.Reflection;
using System.Windows.Forms;
namespace exceltry
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, System.EventArgs e)
{
Excel.Application xlexcel = null;
Excel._Workbook xlWorkbook = null;
Excel._Worksheet xlWorkSheet = null;
Excel.Range oRng;
try
{
//start excel and get application object
oXL = new Microsoft.Office.Interop.Excel.Application();
//open existing workbook
oWB = oXL.Workbooks.Open("C:\\vehicledet.xlsx");
oSheet = (Excel._Worksheet)oWB.ActiveSheet;
//Add table headers going cell by cell.
xlWorkSheet.Cells[1, 1] = "Plate Number";
xlWorkSheet.Cells[1, 2] = "Car Model";
xlWorkSheet.Cells[1, 3] = "Car Brand";
xlWorkSheet.Cells[1, 4] = "Mileage";
//Format A1:D1 as bold, vertical alignment = center.
xlWorkSheet.get_Range("A1", "D1").Font.Bold = true;
xlWorkSheet.get_Range("A1", "D1").VerticalAlignment =
Excel.XlVAlign.xlVAlignCenter;
// insert text at every last row
int _lastRow = xlWorkSheet.Range["A" + xlWorkSheet.Rows.Count].End[Excel.XlDirection.xlUp].Row + 1;
xlWorkSheet.Cells[_lastRow, 1] = textBox1.Text;
xlWorkSheet.Cells[_lastRow, 2] = textBox2.Text;
xlWorkSheet.Cells[_lastRow, 3] = textBox3.Text;
xlWorkSheet.Cells[_lastRow, 4] = textBox4.Text;
//AutoFit columns A:D.
oRng = xlWorkSheet.get_Range("A1", "D1");
oRng.EntireColumn.AutoFit();
//Make sure Excel is not visible and give the user control of Microsoft Excel's lifetime.
xlexcel.Visible = false;
xlexcel.UserControl = true;
//can save update to same file but wont close unless user press x button
xlWorkbook.Save();
MessageBox.Show("Data saved successfully");
xlWorkbook.Close();
//allow excel to auto close by itself
oXL.Quit();
Marshal.ReleaseComObject(oXL);
}
catch (Exception theException)
{
String errorMessage;
errorMessage = "Error: ";
errorMessage = String.Concat(errorMessage, theException.Message);
errorMessage = String.Concat(errorMessage, " Line: ");
errorMessage = String.Concat(errorMessage, theException.Source);
MessageBox.Show(errorMessage, "Error");
}
}
}
(根据反馈进行编辑)见下文。文本框中的数据将自动进入所选的现有excel文件。这是对帮助的巨大赞扬
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Excel = Microsoft.Office.Interop.Excel;
using System.Reflection;
using System.Windows.Forms;
namespace exceltry
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, System.EventArgs e)
{
Excel.Application xlexcel = null;
Excel._Workbook xlWorkbook = null;
Excel._Worksheet xlWorkSheet = null;
Excel.Range oRng;
try
{
//start excel and get application object
oXL = new Microsoft.Office.Interop.Excel.Application();
//open existing workbook
oWB = oXL.Workbooks.Open("C:\\vehicledet.xlsx");
oSheet = (Excel._Worksheet)oWB.ActiveSheet;
//Add table headers going cell by cell.
xlWorkSheet.Cells[1, 1] = "Plate Number";
xlWorkSheet.Cells[1, 2] = "Car Model";
xlWorkSheet.Cells[1, 3] = "Car Brand";
xlWorkSheet.Cells[1, 4] = "Mileage";
//Format A1:D1 as bold, vertical alignment = center.
xlWorkSheet.get_Range("A1", "D1").Font.Bold = true;
xlWorkSheet.get_Range("A1", "D1").VerticalAlignment =
Excel.XlVAlign.xlVAlignCenter;
// insert text at every last row
int _lastRow = xlWorkSheet.Range["A" + xlWorkSheet.Rows.Count].End[Excel.XlDirection.xlUp].Row + 1;
xlWorkSheet.Cells[_lastRow, 1] = textBox1.Text;
xlWorkSheet.Cells[_lastRow, 2] = textBox2.Text;
xlWorkSheet.Cells[_lastRow, 3] = textBox3.Text;
xlWorkSheet.Cells[_lastRow, 4] = textBox4.Text;
//AutoFit columns A:D.
oRng = xlWorkSheet.get_Range("A1", "D1");
oRng.EntireColumn.AutoFit();
//Make sure Excel is not visible and give the user control of Microsoft Excel's lifetime.
xlexcel.Visible = false;
xlexcel.UserControl = true;
//can save update to same file but wont close unless user press x button
xlWorkbook.Save();
MessageBox.Show("Data saved successfully");
xlWorkbook.Close();
//allow excel to auto close by itself
oXL.Quit();
Marshal.ReleaseComObject(oXL);
}
catch (Exception theException)
{
String errorMessage;
errorMessage = "Error: ";
errorMessage = String.Concat(errorMessage, theException.Message);
errorMessage = String.Concat(errorMessage, " Line: ");
errorMessage = String.Concat(errorMessage, theException.Source);
MessageBox.Show(errorMessage, "Error");
}
}
}
最近,我有一个项目,它也会将数据发送到excel文件中,但与您的不同,我的数据来自文本文件,该网站上的某个人帮助我了解如何在excel文件中导出数组的值。在您的情况下,此代码可能会有所帮助
using Excel = Microsoft.Office.Interop.Excel;
Excel.Application exc = new Excel.Application();
exc.Interactive = true;
var excelTemplate = "CompareResult.xlsx"; //Change it with your filename
string FromPath = Path.GetFullPath(excelTemplate); //Get the full path of your excel
//file.
Excel.Workbook wb = exc.Workbooks.Open(FromPath);
Excel.Worksheet sh = wb.Sheets[1];
int _lastRow = xlWorkSheet.Cells[xlWorkSheet.Rows.Count, 1].End[Excel.XlDirection.xlUp].Row + 1;
sh.Cells[row, 1].Value2 = textBox1.Text;
sh.Cells[row, 2].Value2 = textBox1.Text;
sh.Cells[row, 3].Value2 = textBox1.Text;
sh.Cells[row, 4].Value2 = textBox1.Text;
wb.Save(); \\Saving the file when changing
wb.Close();
exc.Quit();
最近,我有一个项目,它也会将数据发送到excel文件中,但与您的不同,我的数据来自文本文件,该网站上的某个人帮助我了解如何在excel文件中导出数组的值。在您的情况下,此代码可能会有所帮助
using Excel = Microsoft.Office.Interop.Excel;
Excel.Application exc = new Excel.Application();
exc.Interactive = true;
var excelTemplate = "CompareResult.xlsx"; //Change it with your filename
string FromPath = Path.GetFullPath(excelTemplate); //Get the full path of your excel
//file.
Excel.Workbook wb = exc.Workbooks.Open(FromPath);
Excel.Worksheet sh = wb.Sheets[1];
int _lastRow = xlWorkSheet.Cells[xlWorkSheet.Rows.Count, 1].End[Excel.XlDirection.xlUp].Row + 1;
sh.Cells[row, 1].Value2 = textBox1.Text;
sh.Cells[row, 2].Value2 = textBox1.Text;
sh.Cells[row, 3].Value2 = textBox1.Text;
sh.Cells[row, 4].Value2 = textBox1.Text;
wb.Save(); \\Saving the file when changing
wb.Close();
exc.Quit();
这是很多不好的做法。要获得此异常并不难,只需在单击按钮1之前单击按钮3。嗨,汉斯。当我点击按钮3时,错误将弹出,其他按钮无法按下。无论如何,按钮3是用来关闭程序的,所以如果我先按下它,我的所有数据都不会被保存(没有区别,因为我甚至不能运行程序:()。我会继续尝试。不使用Excel interop,您可以使用像EPPlus这样的库直接生成xlsx
文件。但您不必担心安装Excel、关闭和正确处理COM对象。这是很多错误做法。不难获得此异常,只需单击按钮1之前单击按钮3。您好。当我单击按钮3时,错误将弹出,其他按钮无法按下。无论如何,按钮3是用来关闭程序的,因此如果我先按下它,我的所有数据都将无法保存(无差异,因为我甚至无法运行程序:()。我会继续尝试。不使用Excel interop,您可以使用像EPPlus这样的库直接生成xlsx
文件。但您不必担心安装Excel、关闭和正确处理COM对象。单击按钮后会立即抛出NRE-xlexcel
为空。另一个严重问题是m是它不使用using
块来确保COM对象被处理。如果抛出错误,Excel将保持打开状态。更新了编码。感谢所有的反馈,这将在单击按钮后立即抛出NRE-xlexcel
为空。另一个严重问题是它不使用using代码>阻止以确保COM对象被释放。如果抛出错误,Excel将保持openHi。更新了编码。感谢所有人的反馈