Excel-DNA项目只用1个文件实现Ribbon CustomUI和CustomTaskpane定制【C#版】
Excel-DNA项目中的自定义功能区和自定义任务窗格需要用到各种命名空间、添加所需文件,才能实现。后来我发现可以把所有代码都写在Class1.cs这个默认文件中。
大家可以在Visual Studio中创建一个类库项目(.Net Framework),然后把默认的Class1.cs中的代码整体替换为下面我贴的这个代码。然后启动调试,就可以看到自定义功能区和任务窗格了。
1 using System.Runtime.InteropServices; 2 using ExcelDna.Integration; 3 using ExcelDna.Integration.CustomUI; 4 using Excel = Microsoft.Office.Interop.Excel; 5 using System.Windows.Forms; 6 namespace Excel_DNA_Template_CS 7 { 8 [ComVisible(true)] 9 public class Class1 :ExcelRibbon,IExcelAddIn 10 { 11 public IRibbonUI R; 12 public override string GetCustomUI(string RibbonID) 13 { 14 string xml = @"<customUI xmlns='http://schemas.microsoft.com/office/2009/07/customui' onLoad='OnLoad'> 15 <ribbon startFromScratch='false'> 16 <tabs> 17 <tab id='Tab1' label='RibbonXmlEditor'> 18 <group id='Group1' label='Author:ryueifu'> 19 <button id='Button1' label='CTP' imageMso='C' onAction='Button1_Click'/> 20 <button id='Button2' label='UnLoad' imageMso='U' onAction='Button2_Click'/> 21 </group> 22 </tab> 23 </tabs> 24 </ribbon> 25 </customUI>"; 26 return xml; 27 } 28 public void OnLoad(IRibbonUI ribbon) 29 { 30 R = ribbon; 31 R.ActivateTab(ControlID: "Tab1"); 32 } 33 public void Button1_Click(IRibbonControl control) 34 { 35 Module1.ctp.Visible = !Module1.ctp.Visible; 36 } 37 public void Button2_Click(IRibbonControl control) 38 { 39 Excel.AddIn ThisAddin = (ExcelDnaUtil.Application as Excel.Application).AddIns["Excel_DNA_Template_CS"]; 40 ThisAddin.Installed= false; 41 } 42 void IExcelAddIn.AutoClose() 43 { 44 Module1.DisposeCTP(); 45 } 46 47 void IExcelAddIn.AutoOpen() 48 { 49 Module1.CreateCTP(); 50 } 51 } 52 public static class Module1 53 { 54 public static UserControl uc; 55 public static CustomTaskPane ctp; 56 public static void CreateCTP() 57 { 58 uc = new UserControl(); 59 ctp = CustomTaskPaneFactory.CreateCustomTaskPane(userControl: uc, title: "CTP"); 60 ctp.DockPosition = MsoCTPDockPosition.msoCTPDockPositionRight; 61 ctp.Visible = true; 62 } 63 public static void DisposeCTP() 64 { 65 ctp.Delete(); 66 ctp = null; 67 } 68 } 69 }