在 excel 中写入单元格的函数

Function to write cells in excel

我从这里得到了一些代码: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 未处理: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;
            }

        }

如您 link 在方法 excel_init 中编写的代码所示,您需要初始化 objsheet。它是在 link:

中的这一行完成的
objsheet = (_Worksheet)appExcel.ActiveWorkbook.ActiveSheet;

对于您问题中的此编辑:

How I call my excel_setValue:

excel_setValue("B10","520");
excel_init("C:\");

这是您使用的执行顺序吗?在 excel_setValue 中使用之前必须先调用 excel_init 并初始化 objsheet。

您可能正在使用 get_Range incorrectly, see this question 来获取更多示例。

您还错误地使用了Range.set_Value,请尝试使用objsheet.get_Range(cellname).set_Value(Excel.XlRangeValueDataType.xlRangeValueDefault,value);