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 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM