【问题标题】:In Excel-DNA adding a new line in context menu at right-click on a cell in a spreadsheet在 Excel-DNA 中,右键单击电子表格中的单元格在上下文菜单中添加新行
【发布时间】:2022-08-07 22:35:27
【问题描述】:
我会在 Excel-DNA 中执行以下操作:
对于引用 xll 的任何工作簿,在工作簿的任何工作表中,右键单击单元格,会出现带有新行的普通菜单(带有“剪切”、“复制”、“粘贴”)称为 \"something\",当单击 \"something\" 时,它会打开一个 \"form\"(例如输入中的两个数字或任何内容)。
使用 Excel-DNA 是不可能的(我在 github 上挖掘了 Excel-DNA 源代码,我没有看到与上下文菜单相关的任何内容),我愿意使用 Excel-Interop 来做。
标签:
c#
excel-interop
excel-dna
【解决方案1】:
我浏览到Excel-DNA's source code on github 并遇到了IExcelAddIn 接口,我在下面的代码中直接实现了该接口:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ExcelDna.Integration;
using ExcelDna.Integration.CustomUI;
using Microsoft.Office.Interop.Excel;
using Office = Microsoft.Office.Core;
using Application = Microsoft.Office.Interop.Excel.Application;
namespace AddinThings
{
public class MyAddin : IExcelAddIn
{
Application xlApp = (Application)ExcelDnaUtil.Application;
private Office.CommandBar GetCellContextMenu()
{
return this.xlApp.CommandBars["Cell"];
}
void exampleMenuItemClick(Microsoft.Office.Core.CommandBarButton Ctrl, ref bool CancelDefault)
{
System.Windows.Forms.MessageBox.Show("Example Menu Item clicked");
}
void IExcelAddIn.AutoOpen()
{
Office.MsoControlType menuItem = Office.MsoControlType.msoControlButton;
Office.CommandBarButton exampleMenuItem = (Office.CommandBarButton)GetCellContextMenu().Controls.Add(menuItem, System.Reflection.Missing.Value, System.Reflection.Missing.Value, 1, true);
exampleMenuItem.Style = Office.MsoButtonStyle.msoButtonCaption;
exampleMenuItem.Caption = "Example Menu Item";
exampleMenuItem.Click += new Microsoft.Office.Core._CommandBarButtonEvents_ClickEventHandler(exampleMenuItemClick);
}
private void ResetCellMenu()
{
GetCellContextMenu().Reset(); // reset the cell context menu back to the default
}
void IExcelAddIn.AutoClose()
{
ResetCellMenu();
}
}
}
【解决方案2】:
对于 Excel 2010+,还可以在功能区中自定义上下文菜单
xml。
<customUI xmlns="http://schemas.microsoft.com/office/2009/07/ customui">
<ribbon>
[.....]
</ribbon>
<contextMenus>
<contextMenu idMso="ContextMenuCell">
<button idMso="FileSave" insertBeforeMso="Cut" />
<button id="MyButton" label="Toggle Case Upper/Lower/Proper" insertBeforeMso="Cut" onAction="ToggleCaseMacro" imageMso="HappyFace"/>
<menu id="MySubMenu" label="Case Menu" insertBeforeMso="Cut" >
<button id="Menu1Button1" label="Upper Case" imageMso="U" onAction="UpperMacro"/>
<button id="Menu1Button2" label="Lower Case" imageMso="L" onAction="LowerMacro"/>
<button id="Menu1Button3" label="Proper Case" imageMso="P" onAction="ProperMacro"/>
</menu>
<menuSeparator id="MySeparator" insertBeforeMso="Cut" />
</contextMenu>
</contextMenus>
</customUI>