如何通过C#中的ExcelDNA访问excel中选择的范围?

问题描述 投票:0回答:1

我是使用Excel DNA和C#编程的菜鸟。这必须是基本问题之一,如果已经在SO上得到回答,那么如果我朝那个方向指出,我会感到非常高兴。我试图将单击按钮时将Excel工作表上活动的任何范围或单元格发送到相应的C#函数。

这是我的Controller类。

using System;
using ExcelDna;
using Excel = Microsoft.Office.Interop.Excel;
//Other dependencies
namespace My_Prj
{
  [ComVisible(true)]
  public class RibbonController : ExcelRibbon
  {
     return @"
     <customUI xmlns='http://schemas.microsoft.com/office/2006/01/customui'>
  <ribbon>
    <tabs>
      <tab id='tab1' label='Temp Tab'>
        <group id='group1' label='Temp Group'>
          <button id='button1' label='Attach Db' onAction='OnButton1Pressed'/>
          <button id='button2' label='Detach Db' onAction='OnButton2Pressed'/>
          <button id='button3' label='Write Data'   onAction='OnButton3Pressed'/>
        </group >
      </tab>
    </tabs>
  </ribbon>
</customUI>";
 }
public void OnButton1Pressed(IRibbonControl control)
    {
        bool status = Main.Attach();
        //+control.Id
        MessageBox.Show("DB session Attach status: [" + status + "] ");
    }
    public void OnButton2Pressed(IRibbonControl control)
    {
        bool status = Main.Detach();
        MessageBox.Show("DB session Detach status: [" + status + "]");
    }
    public void OnButton3Pressed(IRibbonControl control)
    {
        // Code to access range

    }

这是我的主班。

using System;
using ExcelDna;
using Excel = Microsoft.Office.Interop.Excel;
// Other dependencies
namespace My_Prj
{
   public class Main
   {
      // Class variables
      [ExcelFunction(Category = "Main", Description = "Attach DB", Name = "Attach_DB")]
      public static bool Attach()
      {
        //Connect to DB;
        return status;
      }
      [ExcelFunction(Category = "Main", Description = "Detach DB", Name = "Detach_DB")]
      public static bool Detach()
      {
        //Disconnect from DB;
        return status;
      }
      [ExcelFunction(Category = "Main", Description = "Write Data", Name = "Write_Data")]
      public static bool WriteData(Object[,] data)
      {
        //Write data;
      }
  }
}

显然,如果我从excel调用Write_Data函数并选择范围,则可以将数据持久保存在DB中。我的目标是在excel中选择范围或单元格后单击第三个按钮,并将该数据保留在DB中。我的代码能够处理不同的数据(一个单元格或一系列单元格)。

如果需要任何其他信息,请告诉我。

c# excel excel-addins excel-dna xll
1个回答
0
投票

从功能区事件处理程序中,您可以通过Excel COM API访问ExcelDnaUtil.Application,获得对活动工作表的引用,并获得所选范围并检查其值。

安装ExcelDna.Interop NuGet软件包使其更容易(因此您可以获取IntelliSense),并使用ExcelDnaUtil.Application实例访问COM API。

例如

try
{
    var excelApp = (Microsoft.Office.Interop.Excel.Application)ExcelDnaUtil.Application;

    // Use excelApp to access the selected sheet, range, etc.
    // the same way you would do with VBA
}
catch (Exception ex)
{
    MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
© www.soinside.com 2019 - 2024. All rights reserved.