Excel-DNA專案只用1個檔案實現Ribbon CustomUI和CustomTaskpane定製【C#版】
阿新 • • 發佈:2018-12-15
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 }