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

本文关键字:单元格 工作 活动 Excel | 更新日期: 2023-09-27 18:34:20

对于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";

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

现在我找到了解决方案:

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/