[英]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
定义范围,该范围在创建新表单之前已定义为活动表单。 仅仅因为您选择了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";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.