在excel中编写单元格的函数
本文关键字:单元格 函数 excel | 更新日期: 2023-09-27 17:54:57
我从这里得到一点代码:http://forum.codecall.net/topic/71788-reading-excel-files-in-c/它工作得很好,很容易理解。它只能读取excel单元格,我也想写一些。所以我想在main中这样做: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 was unhandled: Exception from 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;
}
}
如您在方法excel_init
中链接的代码所示,您需要初始化objsheet
。它在链接中的这一行完成:
objsheet = (_Worksheet)appExcel.ActiveWorkbook.ActiveSheet;
在你的问题中编辑:
How I call my excel_setValue:
excel_setValue("B10","520");
excel_init("C:''");
这是你使用的执行顺序吗?你必须先调用excel_init
并在excel_setValue
中使用它之前初始化objsheet。
你可能没有正确地使用get_Range,更多的例子参见这个问题。
您还使用了Range。set_Value不正确,尝试使用objsheet.get_Range(cellname).set_Value(Excel.XlRangeValueDataType.xlRangeValueDefault,value);