我从这里得到了一些代码:http://forum.codecall.net/topic/71788-reading-excel-files-in-c/,它工作正常,对我来说很容易理解。它只能读取excel单元格,我也想写一些。 所以我想在我的主要做到这一点:excel_setValue(“C10”,“520”);在excel中写入单元格的函数
这是我试过的功能:
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方法。 – JWiley
在这个方法中(这个范围),'objsheet'不存在。还是在封装类中定义? – Melvin
在我的主要问题中编辑了这2个问题 – wouter