【发布时间】:2015-06-09 22:39:14
【问题描述】:
我从这里得到了一些代码:http://forum.codecall.net/topic/71788-reading-excel-files-in-c/,它运行良好并且对我来说很容易理解。它只能读取excel单元格,我也想写一些。 所以我想在我的主要做这个:excel_setValue("C10", "520");
这是我尝试的功能:
private static Microsoft.Office.Interop.Excel.ApplicationClass appExcel;
private static Workbook newWorkbook = null;
private static _Worksheet objsheet = null;
static string excel_setValue(string cellname, string value)
{
if (objsheet.get_Range(cellname).get_Value().ToString() == string.Empty) // Here is error
{
Console.WriteLine("watch out u trying to overwrite files");
}
else
{
objsheet.get_Range(cellname).set_Value(value);
}
}
它告诉我:NullReferenceExpection 未处理 - 对象引用未设置为对象的实例。
我只放这个时遇到的另一个错误:
static void excel_setValue(string cellname, string value)
{
//if (objsheet.get_Range(cellname).get_Value().ToString() == string.Empty)
//{
// Console.WriteLine("kijk uit je probeerd cellen te overschrijven");
//}
//else
//{
objsheet.get_Range(cellname).set_Value(value);
//}
}
错误:COMException 未处理:来自 HRESULT 的异常:0x800A03EC
我如何称呼我的 excel_setValue:
excel_init("C:\\");
excel_setValue("B10","520");
excel_init:
static void excel_init(String path)
{
appExcel = new Microsoft.Office.Interop.Excel.ApplicationClass();
if (System.IO.File.Exists(path))
{
// then go and load this into excel
newWorkbook = appExcel.Workbooks.Open(path, true, true);
objsheet = (_Worksheet)appExcel.ActiveWorkbook.ActiveSheet;
}
else
{
Console.WriteLine("Unable to open file!");
System.Runtime.InteropServices.Marshal.ReleaseComObject(appExcel);
appExcel = null;
}
}
【问题讨论】:
-
如果 get_Range 返回 null,您将收到 get_Value() 的错误。请说明您是如何调用 excel_setValue 方法的。
-
在此方法(此范围)内,
objsheet不存在。还是在封装类中定义的? -
在我的主要问题中编辑了这两个问题
-
好的,看起来你没有像梅尔文指出的那样设置 objsheet。
private static _Worksheet objsheet = null;这里为null,在调用get_Range之前从未设置过@ -
我将我的初始化添加到问题中,它正在发生
标签: c# excel nullreferenceexception