C# vsto 添加工作表

C# vsto add worksheet

我的所有代码都有效,但是当我写入新工作表中的单元格时,写入第一个 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";
        }
    }
}

您正在根据 excelSheet 定义范围,您在创建新范围之前将其定义为活动 sheet。仅仅因为您 select 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";