Excel更改活动工作表的单元格值

时间:2016-02-12 17:28:38

标签: c# excel excel-interop

对于excel 2010插件,我需要一种方法来更改活动工作表的单元格值。

此代码有效,但会打开一个新的Excel窗口。 如何更改此项,以编辑活动工作表中的值?

Microsoft.Office.Interop.Excel.Application objApp;
Microsoft.Office.Interop.Excel.Workbook objBook;

Microsoft.Office.Interop.Excel.Sheets objSheets;
Microsoft.Office.Interop.Excel._Worksheet workSheet;


objApp = (Microsoft.Office.Interop.Excel.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");
objApp.Visible = true;
objBook = (Microsoft.Office.Interop.Excel.Workbook)objApp.ActiveWorkbook;

if (objBook == null)
    {
       objBook = objApp.Workbooks.Add();
    }

// get the collection of sheets in the workbook

objSheets = objBook.Worksheets;

// get the first and only worksheet from the collection of worksheets

workSheet = (Microsoft.Office.Interop.Excel.Worksheet)objSheets.get_Item(1);

workSheet.Cells[1, "A"] = "wert1";

1 个答案:

答案 0 :(得分:0)

现在我找到了解决方案:

Microsoft.Office.Interop.Excel.Workbook objBook;
Microsoft.Office.Interop.Excel.Sheets objSheets;
Microsoft.Office.Interop.Excel._Worksheet workSheet;

objBook = (Workbook)Globals.ThisAddIn.Application.ActiveWorkbook;

if (objBook == null)
    {
       objBook = objApp.Workbooks.Add();
    }

// get the first and only worksheet from the collection of worksheets

workSheet = (Microsoft.Office.Interop.Excel.Worksheet)objBook.ActiveSheet;

workSheet.Cells[1, "A"] = "value1A";

来源: http://www.dreamincode.net/forums/topic/199576-getting-current-excel-application-or-workbook-in-c%23/