C#vsto添加工作表

时间:2018-07-18 15:38:02

标签: c# excel vsto

我所有的代码都有效,但是当我写入新工作表中的单元格时,将写入第一个工作表Sheet1。在单击事件结束之前,不会创建工作表。

在单击事件之后,我是否还会触发另一个事件来填充创建的新工作表?

我该如何解决?谢谢...

using Microsoft.Office.Interop.Excel;
using System.Runtime.InteropServices;
using Microsoft.Office.Tools.Ribbon;
using Excel = Microsoft.Office.Interop.Excel;


namespace Prototype
{
    public partial class Ribbon1
    {
        private Excel.Application xlApp;
        private Workbook xlWorkBook;
        private Worksheet xlWorkSheet;
        private dynamic excelSheet;
        private Range range;

        private void Ribbon1_Load(object sender, RibbonUIEventArgs e) { }

        private void Button1_Click(object sender, RibbonControlEventArgs e)
        {
            xlApp = (Excel.Application)Marshal.GetActiveObject("Excel.Application");
            xlApp.Visible = true;
            xlWorkBook = xlApp.ActiveWorkbook;
            xlWorkSheet = xlWorkBook.Worksheets.Item[1];
            excelSheet = xlWorkBook.ActiveSheet;
            xlApp = (Excel.Application)Marshal.GetActiveObject("Excel.Application");
            xlWorkBook = xlApp.ActiveWorkbook;

            xlWorkBook.Sheets.Add(After: xlWorkBook.Sheets[xlWorkBook.Sheets.Count]);
            xlWorkSheet = xlWorkBook.Worksheets.Item[2];
            xlWorkSheet.Select();
            xlWorkSheet.Name = "Dashboard";

            xlWorkBook.Sheets.Add(After: xlWorkBook.Sheets[xlWorkBook.Sheets.Count]);
            xlWorkSheet = xlWorkBook.Worksheets.Item[3];
            xlWorkSheet.Select();
            xlWorkSheet.Name = "Dashboard2";

            xlWorkBook.Worksheets.Add(After: xlWorkBook.Sheets[xlWorkBook.Sheets.Count]);
            xlWorkSheet = xlWorkBook.Worksheets.Item[4];
            xlWorkSheet.Select();
            xlWorkSheet.Name = "Dashboard3";

            xlWorkSheet = (Worksheet)xlWorkBook.Worksheets["Dashboard"];
            xlWorkSheet.Select();
            range = excelSheet.Cells[1, 1];
            range.Value2 = "Test";

            xlWorkSheet = (Worksheet)xlWorkBook.Worksheets["Dashboard2"];
            xlWorkSheet.Select();
            range = excelSheet.Cells[1, 1];
            range.Value2 = "Test";
        }
    }
}

1 个答案:

答案 0 :(得分:0)

您要基于excelSheet定义范围,该范围在创建新工作表之前已定义为活动工作表。仅仅因为您选择了xlWorkSheet并不意味着excelSheet更改了值。您的代码应为

xlWorkSheet = (Worksheet)xlWorkBook.Worksheets["Dashboard"];
range = xlWorkSheet.Cells[1, 1];
range.Value2 = "Test";

xlWorkSheet = (Worksheet)xlWorkBook.Worksheets["Dashboard2"];
range = xlWorkSheet.Cells[1, 1];
range.Value2 = "Test";